【问题标题】:How do multiple clients communicate using messaging system? (Python)多个客户端如何使用消息系统进行通信? (Python)
【发布时间】:2014-01-15 17:46:31
【问题描述】:
【问题讨论】:
标签:
python
sockets
tcp
chat
message
【解决方案1】:
def broadcast_data (sock, message):
#Do not send the message to master socket and the client who has send us the message
for socket in CONNECTION_LIST:
if socket != server_socket and socket != sock :
try :
socket.send(message)
except :
# broken socket connection may be, chat client pressed ctrl+c for example
socket.close()
CONNECTION_LIST.remove(socket)
这个函数可以作为发送函数的起点
def send_data (sock, message):
#send message to only one client
#sock is the socket of the client to send to
try :
sock.send(message)
except :
# broken socket connection may be, chat client pressed ctrl+c for example
sock.close()
CONNECTION_LIST.remove(socket)
那么你可以有一个套接字字典,将它们与用户名相关联
usernameSockets={}
usernameSockets[username]=socket_for_user_name
那么你可以像这样调用 send_data 函数
send_data(usernameSockets[username],message)
在您链接的代码中,没有获取用户名的方法,因此您必须让客户端在连接时将其用户名发送到服务器,以便能够像我上面提到的那样填充字典。