Python Socket编程服务端无法向客户端列表转发广播消息求助
问题根因
- 你使用的是TCP面向连接通信,
sendto是UDP协议专用的发送方法,在TCP场景下传入的地址参数会被直接忽略,你所有消息都通过触发指令的客户端连接connection发送,自然只有发送方自己能收到消息。 - 你已经将所有客户端的有效连接对象存储在
conList列表中,但广播逻辑没有使用该列表,反而遍历了无意义的IP地址列表ipList。 - 缺少客户端断开后的连接清理逻辑,后续会出现无效连接报错。
修复方案
仅需要修改server.py中的threaded_client函数即可,客户端代码无需调整,修改后的完整函数如下:
def threaded_client(connection, addr): connection.send(str.encode('Welcome to the Server')) while True: data = connection.recv(2048) if not data: break msg = data.decode() print(msg) if msg[0:2] == '!q': # 客户端主动退出时清理无效连接 if connection in conList: conList.remove(connection) if addr in ipList: ipList.remove(addr) connection.close() break elif msg[0:8] == '!sendall': # 遍历所有有效客户端连接发送广播 for client_con in conList: # 不需要排除发送方就删掉下面这个if判断 if client_con != connection: try: client_con.sendall(b'Sending this to All!') except: # 发送失败说明客户端已断开,清理连接 conList.remove(client_con) else: reply = 'Server Says: ' + msg connection.sendall(str.encode(reply)) # 异常断开时也清理连接 if connection in conList: conList.remove(connection) if addr in ipList: ipList.remove(addr) connection.close()
内容的提问来源于stack exchange,提问作者Junaid
相关产品推荐
相关产品推荐

