【问题标题】:I want to broadcast to different client我想广播给不同的客户
【发布时间】:2021-11-21 03:35:34
【问题描述】:

所以这段代码广播到所有连接到它的客户端(包括它自己),但我想广播到一个特定的客户端。我该怎么做?

import socket, threading                                                #Libraries import

host = '127.0.0.1'                                                      #LocalHost
port = 7978                                                            #Choosing unreserved port

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)              #socket initialization
server.bind((host, port))                                               #binding host and port to socket
server.listen()

clients = []
nicknames = []

def broadcast(message):                                                 #broadcast function declaration
    for client in clients:
        print(client, type(client))
        client.send(message)

def handle(client):                                         
    while True:
        try:                                                            #recieving valid messages from client
            message = client.recv(1024)
            broadcast(message)
        except:                                                         #removing clients
            index = clients.index(client)
            clients.remove(client)
            client.close()
            nickname = nicknames[index]
            broadcast('{} left!'.format(nickname).encode('ascii'))
            nicknames.remove(nickname)
            break

def receive():                                                          #accepting multiple clients
    
    while True:
        client, address = server.accept()
        print("Connected with {}".format(str(address)))       
        client.send('NICKNAME'.encode('ascii'))
        nickname = client.recv(1024).decode('ascii')
        nicknames.append(nickname)
        clients.append(client)
        print("Nickname is {}".format(nickname))
        broadcast("{} joined!".format(nickname).encode('ascii'))
        client.send('Connected to server!'.encode('ascii'))
        thread = threading.Thread(target=handle, args=(client,))
        thread.start()
        
receive()

如果客户端发送消息,服务器会将消息广播给所有客户端,包括发送消息的客户端。有没有办法解决这个问题?

【问题讨论】:

  • 如果您不想向客户端发送消息,请不要调用 client.send(message)
  • 我只想将消息发送给其他客户端,而不是发送消息的客户端。
  • 所以不要调用那个客户端的发送函数
  • 在代码方面我该怎么做?
  • 你向除那个之外的所有客户端发送消息

标签: python multithreading sockets websocket


【解决方案1】:

将广播功能改为如下:

import socket, threading                                                #Libraries import

host = '127.0.0.1'                                                      #LocalHost
port = 7978                                                            #Choosing unreserved port

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)              #socket initialization
server.bind((host, port))                                               #binding host and port to socket
server.listen()

clients = []
nicknames = []

def broadcast(message, clientt):                                                 #broadcast function declaration
    for client in clients:
        if client == clientt:
            continue
        else:
            client.send(message)
    # for client in clients:
    #     print(client, type(client))
    #     client.send(message)

def handle(client):                                         
    while True:
        try:                                                            #recieving valid messages from client
            message = client.recv(1024)
            broadcast(message, client)
        except:                                                         #removing clients
            index = clients.index(client)
            clients.remove(client)
            client.close()
            nickname = nicknames[index]
            broadcast('{} left!'.format(nickname).encode('ascii'), client)
            nicknames.remove(nickname)
            break

def receive():                                                          #accepting multiple clients
    
    while True:
        client, address = server.accept()
        print("Connected with {}".format(str(address)))       
        client.send('NICKNAME'.encode('ascii'))
        nickname = client.recv(1024).decode('ascii')
        nicknames.append(nickname)
        clients.append(client)
        print("Nickname is {}".format(nickname))
        broadcast("{} joined!".format(nickname).encode('ascii'), client)
        client.send('Connected to server!'.encode('ascii'))
        thread = threading.Thread(target=handle, args=(client,))
        thread.start()
        
receive()

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 2016-07-21
  • 2018-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多