Python 套接字 - 多个客户端到一台服务器,连接不良或线程不良?

Python sockets - multiple clients to one server, bad connection or bad threading?

我正在尝试在 python 中创建 p2p 聊天。这个想法是让客户端在出现故障时能够成为服务器。这是出于学习目的,所以我只是在我的笔记本电脑上进行本地操作。

但截至目前,我正在努力解决客户端与服务器之间的通信问题。

我为服务器打开了一个终端 window。 2 个终端 windows 供客户使用。

如果我连接两个客户端,都可以向服务器发送消息,服务器将消息广播给所有客户端。 但是在来自第二个客户端的 1 条消息之后,只有一个客户端可以发送消息,但是服务器从两个客户端打印出端口。

示例输出:https://i.imgur.com/nJrycos.png

我疯狂地用谷歌搜索。 我试过将套接字创建放在 while 循环中(参见下面的代码)。

class Server:
    connections = []

    def __init__(self):
        print("server created")

        # I have tried putting this part in the while loop below
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        hostname = socket.gethostname()
        host = socket.gethostbyname(hostname)
        port = 5001
        sock.bind((host, port))
        print("Hosting server on " + host + ":" + str(port) + " hostname: " + hostname)

        sock.listen(1)  # I have tried changing the value from 1 to 2, 5, 10 etc but no difference

        while True:
            connection, client_address = sock.accept()
            print(str(client_address) + " connected!")

            # create new thread
            listener_thread = Thread(target=self.server_listener, args=(connection, client_address))
            listener_thread.daemon = True
            listener_thread.start()

            self.connections.append(connection)


    def server_listener(self, connection, client_address):
        while True:
            chunk = connection.recv(1024)
            if not chunk:
                print(str(client_address) + " disconnected")
                break
            elif chunk[0:3] == b'msg':
                # Send out message to other clients connected
                for connection in self.connections:
                    connection.send(chunk[3:].decode())

            print(str(client_address) + ':' + chunk[3:])

我的客户端class 基本上是一样的,但是使用的是connect 而不是bind。客户端也有一个监听服务器消息的线程方法。

我没有收到任何错误消息,所以我什至不知道线程或网络部分是否有问题。

我希望服务器应该能够有多个线程并能够连接多个客户端并让它们能够通信。

您正在覆盖

中的连接

    def server_listener(self, connection, client_address):
        ...
            elif chunk[0:3] == b'msg':
                # Send out message to other clients connected
                for connection in self.connections: << HERE 
                    connection.send(chunk[3:].decode())

将 self.connections 中的连接更改为 self.connections 中的 c 并尝试。