【问题标题】:How do multiple clients communicate using messaging system? (Python)多个客户端如何使用消息系统进行通信? (Python)
【发布时间】:2014-01-15 17:46:31
【问题描述】:

我有一个服务器监听所有连接到它的客户端,每个客户端都应该有这个“用户名”来识别它们,但我被困在这里......当客户端想要发送消息时另一个客户端,它们将另一个客户端的用户名作为发送到服务器的消息中的第一个单词发送。然后我不知道如何将消息定向到正确的套接字(接收客户端)。我应该如何将客户端链接到其套接字?所以我可以调用socket.send??

我目前正在修改这个网站的代码:http://www.binarytides.com/code-chat-application-server-client-sockets-python/

谢谢!

【问题讨论】:

    标签: 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)
    

    在您链接的代码中,没有获取用户名的方法,因此您必须让客户端在连接时将其用户名发送到服务器,以便能够像我上面提到的那样填充字典。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多