multithreading - multithreaded tcp server python -


i trying create multi-threaded tcp server in python. when new client accepted, goes new created thread. however, when earlier clients send data, looks newly created thread intercept them, server side newer clients speaking!

here code:

nbre = 1  class clientthread(threading.thread):     def __init__(self, channel, connection):       global nbre       nbre = nbre + 1       print("this thread "+str(nbre)+" speaking")       self.channel = channel       self.connection = connection       threading.thread.__init__(self)     def run(self):       print(connection[0]+':'+str(connection[1])+'<'+str(nbre)'> connected!')       try:          while true:              data = self.channel.recv(1024)              if data:                print(connection[0]+':'+str(connection[1])+'<'+str(nbre)+'> '+str(data.strip('\n')))              else:                break       finally:          print(connection[0]+':'+str(connection[1])+'<'+str(nbre)+'> exited!')          self.channel.close()  server = socket.socket(socket.af_inet, socket.sock_stream) server.setsockopt(socket.sol_socket, socket.so_reuseaddr, 1) server.bind(('', 4747)) server.listen(0) while true:    channel, connection = server.accept()    clientthread(channel, connection).start() 

here got when launched , telnet clients sending "hello" first client, "bonjour" second 1 :

 $ python simple_thread.py  thread 2 speaking  # new connection 127.0.0.1:33925> connected! 127.0.0.1:33925<2> hello thread 3 speaking  # new connection 127.0.0.1:33926> connected! 127.0.0.1:33926<3> bonjour # last connected says "bonjour" (ok here) 127.0.0.1:33926<3> hello   # first connected re-send "hello" in thread 3?! 

why secondly sent "hello" not poping thread 2? , how make happend, can reply server side appropriate client?

many thanks! (thread newbie here :/)

the news is, works, logging broken. here use nbre, number of threads, not number of current thread:

           print(connection[0]+':'+str(connection[1])+'<'+str(nbre)+'> '+str(data.strip('\n'))) 

so make work, store current thread's number on thread object, , use instead. this:

   def __init__(self, channel, connection):      global nbre      nbre = nbre + 1      self.number = nbre 

there similar problem connection object. logging using connection instead of self.connection. you'd error, because while loop @ bottom creates global connection variable, 1 gets picked instead. use self.connection in logging instead.

for own sanity, i'd recommend extracting logging function, , using string.format:

def log(self, message):    print('{}:{}<{}> {}'.format(self.connection[0], str(self.connection[1]), self.number, message) 

so can write self.log('thread started') instead of repeating log format each time.


Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -