套接字,而真正的循环不能正常工作

时间:2018-01-04 20:46:49

标签: python loops sockets while-loop

我想问你关于套接字中的while循环的工作原理。 问题是,当我启动app时,服务器正在等待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()

1 个答案:

答案 0 :(得分:1)

您没有正确调用该主题。您立即致电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))