sockets - Multi Threaded TCP server in Python -


i have created simple multi threaded tcp server using python's threding module. server creates new thread each time new client connected.

#!/usr/bin/env python  import socket, threading  class clientthread(threading.thread):      def __init__(self,ip,port):         threading.thread.__init__(self)         self.ip = ip         self.port = port         print "[+] new thread started "+ip+":"+str(port)       def run(self):             print "connection : "+ip+":"+str(port)          clientsock.send("\nwelcome server\n\n")          data = "dummydata"          while len(data):             data = clientsock.recv(2048)             print "client sent : "+data             clientsock.send("you sent me : "+data)          print "client disconnected..."  host = "0.0.0.0" port = 9999  tcpsock = socket.socket(socket.af_inet, socket.sock_stream) tcpsock.setsockopt(socket.sol_socket, socket.so_reuseaddr, 1)  tcpsock.bind((host,port)) threads = []   while true:     tcpsock.listen(4)     print "\nlistening incoming connections..."     (clientsock, (ip, port)) = tcpsock.accept()     newthread = clientthread(ip, port)     newthread.start()     threads.append(newthread)  t in threads:     t.join() 

then opened 2 new terminals , connected server using netcat. then, when type , send first data server using first terminal connected, reply server comes other terminal , first connection got disconnected. guessed reason doubtful whether happens because clientsock variable overwritten refers second connection's socket. correct , how avoid that?

is there way other using array limited number of socket variables , using each variable each connection?

you should pass client sock thread ip address , 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 "+ip+":"+str(port)      def run(self):         # use self.socket send/receive  ... (clientsock, (ip, port)) = tcpsock.accept() newthread = clientthread(ip, port, clientsock) ... 

Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -