Multi Threaded TCP server in Python

前端 未结 2 710
盖世英雄少女心
盖世英雄少女心 2020-12-05 07:32

I have created a simple multi threaded tcp server using python\'s threding module. This server creates a new thread each time a new client is connected.

#!/u         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 08:29

    You should pass the client sock to the thread like you do with the ip address and the port:

    class ClientThread(threading.Thread):
    
        def __init__(self, ip, port, socket):
            threading.Thread.__init__(self)
            self.ip = ip
            self.port = port
            self.socket = socket
            print "[+] New thread started for "+ip+":"+str(port)
    
        def run(self):
            # use self.socket to send/receive
    
    ...
    (clientsock, (ip, port)) = tcpsock.accept()
    newthread = ClientThread(ip, port, clientsock)
    ...
    

提交回复
热议问题