Python 连接多个客户端 - 聊天应用

Python Socket multiple clients - chat app

嘿,我正在开发一个聊天应用程序,目前无法进一步了解。不同的客户端连接到服务器,可以成功发送消息。但是只显示来自一个客户端的消息,而不显示来自第二个客户端的消息。

import socket
import _thread

s = socket.socket()
host = socket.gethostname()
print("Server wird auf folgendem Host gestartet: ", host)
port = 8080
s.bind(('127.0.0.1', 50010))
s.listen()
print("Server erfolgreich verbunden")
print("Server wartet auf Verbindungen...")


def serverlisten():
    while True:
        s.listen()
        conn, addr = s.accept()
        print(addr, " hat sich mit dem Server verbunden und ist online")

_thread.start_new_thread(serverlisten, ())

conn, addr = s.accept()
print(addr, " hat sich mit dem Server verbunden und ist online")


while True:
    incoming_message = conn.recv(1024)
    incoming_message = incoming_message.decode()
    print(addr, incoming_message)

首先您需要决定您打算使用的连接类型: 对于简单的聊天应用程序,我建议使用 UDP。 SOCK_DGRAM (UDP) 和 SOCK_STREAM (TCP) 之间的区别解释如下:What is SOCK_DGRAM and SOCK_STREAM?

import socket

port = 50010
s = socket(AF_INET, SOCK_DGRAM)
# reuse the port otherwise it will be blocked if the connection is not closed
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) 
s.bind(('127.0.0.1',port))

现在没有理由使用 s.accept 和 s.listen 函数,因为以下函数已经完成了所有需要的工作:

while True:
try:
    data,addr = s.recvfrom(512) # number of bytes in the message
    msg = data.decode('utf-8')
    # here you can start a thread if multiple users connect simultaneously 
    time.sleep(0.001)
    
except KeyboardInterrupt:
    print('closed by Keyboard Interrupt')
    sock.close()

这是一个正常运行的 python UPD 服务器。但不是 Messenger 应用程序,因为仅接收消息。如果你想要一个信使应用程序,你需要在通信的双方都有一个服务器和一个客户端。

    cmdOut = "Hello other side of the communication"
    byteOut = bytes(cmdOut.encode("utf-8"))     # Convert Server reply to bytes    
    s.sendto(byteOut,otherIP) # Send Server Reply back

我建议在通信的每一端使用不同的端口。