我想问一下套接字中while循环的工作原理。
问题是,当我启动应用程序时,服务器正在等待While True的连接。但是,如果有人连接,服务器将不接受其他连接。 While True循环冻结。

我的代码:

import socket
import threading

class Server(object):

    def __init__(self, host="localhost", port=5335):
        """Create socket..."""
        self.host = host
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.bind((self.host, self.port))
        self.sock.listen(0)
        self.clients = []
        print("Server is ready to serve on adress: %s:%s..."%(self.host, self.port))

        while True:
            client, addr = self.sock.accept()
            print("There is an connection from %s:%s..."%addr)

            t = threading.Thread(target=self.threaded(client, addr))
            t.daemon = True
            t.start()

        self.sock.close()

    def threaded(self, client, adress):
        """Thread client requests."""
        while True:
            data = client.recv(1024)
            print("%s:%s : %s"%(adress[0], adress[1], data.decode('ascii')))
            if not data:
                print("Client %s:%s disconnected..."%adress)
                break

if __name__ == "__main__":
    Server()

最佳答案

您没有正确调用线程。您正在立即调用self.threaded(client, addr),然后将结果传递给threading.Thread()

换句话说,这是:

t = threading.Thread(target=self.threaded(client, addr))

...与此相同:
result = self.threaded(client, addr)
t = threading.Thread(target=result)

您需要这样称呼它:
t = threading.Thread(target=self.threaded, args=(client, addr))

10-08 18:59