2014-01-15 60 views
0

我有一臺服務器正在監聽連接到它的所有客戶端,並且每個客戶端都應該有他們識別的這個「用戶名」,但我在這裏被卡住......當客戶端想要發送一個消息發送到另一個客戶端,他們發送另一個客戶端的用戶名作爲發送到服務器的消息中的第一個字。然後,我不知道如何將消息定向到正確的套接字(接收客戶端)。我應該如何將客戶端連接到它的套接字?所以我可以調用socket.send?多個客戶端如何使用消息傳遞系統進行通信? (Python)

我目前正在修改從本網站代碼:http://www.binarytides.com/code-chat-application-server-client-sockets-python/

謝謝!

回答

0
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) 

該功能可以作爲一個起點,一個發送功能可以有插座他們與用戶名關聯

usernameSockets={} 
usernameSockets[username]=socket_for_user_name 

,那麼你的字典

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) 

那麼你可以調用send_data函數,如

send_data(usernameSockets[username],message) 

在你鏈接的代碼中沒有獲取用戶名的方法,所以你必須讓客戶端發送他們的用戶名到服務器,當他們連接到能夠填充像我上面提到的字典。

相關問題