簡體   English   中英

多線程tcp服務器python

[英]multithreaded tcp server python

我正在嘗試在python中創建多線程TCP服務器。 接受新客戶端后,它將轉到新創建的線程。 但是,當較早的客戶端發送數據時,看起來像新創建的線程攔截了它們,因此從服務器端看來,只有較新的客戶端正在講話!

這是我的代碼:

Nbre = 1

class ClientThread(threading.Thread):

   def __init__(self, channel, connection):
      global Nbre
      Nbre = Nbre + 1
      print("This is 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()

這是啟動后通過telnet客戶端向第一個客戶端發送“ Hello”,向第二個客戶端發送“ Bonjour”得到的結果:

 $ python simple_thread.py 
This is thread 2 speaking  # new connection
127.0.0.1:33925> Connected!
127.0.0.1:33925<2> hello
This is 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" but in thread 3?!

為什么第二個發送的“ hello”沒有從線程2彈出? 以及如何實現它,以便我可以從服務器端答復適當的客戶端?

非常感謝! (在這里線程新手:/)

好消息是,它可能有效,但是您的日志記錄已損壞。 在這里,您使用Nbre ,它是線程數,而不是當前線程數:

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

因此,要使此工作有效,請將當前線程的編號存儲在線程對象上,然后改用該編號。 像這樣:

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

connection對象也有類似的問題。 日志記錄使用的是connection而不是self.connection 通常,您會得到一個錯誤,但是由於底部的while循環會創建一個全局connection變量,因此該變量會被拾取。 因此,請在日志記錄中使用self.connection

為了您自己的理智,我還建議將日志記錄提取到一個函數中,並使用string.format

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

因此,您可以只編寫self.log('Thread started')而不必每次都重復日志格式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM