簡體   English   中英

簡單的多線程服務器客戶端程序

[英]Simple multithreaded Server Client Program

我有一個用於簡單游戲的多線程服務器和客戶端程序。 每當客戶端退出游戲時,我都會嘗試使用 try catch "except BrokenPipeError" 來捕獲異常並通知其他玩家。 我也想結束退出的客戶端線程; 但是,我接受這樣的輸入:

while True:
            client = serverSocket.accept()
            t = ServerThread(client)
            t.start()

我嘗試使用帶有 stop() 函數的線程事件; 但是,我相信我不能使用 .join 語句退出線程,因為我接受輸入的方式。 我應該如何結束強制退出客戶端。 我知道多處理庫有一個終止函數,但我也需要使用線程庫。 我試過 os_exit(1) 但我相信這個命令會殺死整個過程。 此類程序的標准退出流程是什么?

首先join()除了等待線程停止之外什么都不做。 線程到達線程子程序結束時停止。 例如

class ServerThread(threading.Thread):

   def __init__(self,client,name):
      super().__init__(self)
      self.client = client
      self.name = name

   def inform(self,msg):
      print("{}: got message {}".format( self.name, msg ))
      self.client[0].send(msg)

   def run(self):
      while True:
         try:
            self.client[0].recv(1024)
         except BrokenPipeError: #client exits
            # do stuff
            break # -> ends loop
      return # -> thread exits, join returns

如果您想通知其他客戶有人離開了,我會制作另一個監控線程

class Monitoring(threading.Thread):

   def __init__(self):
      super().__init__(self,daemon=True) # daemon means thread stops when main thread do
      self.clients=[]

   def add_client(self,client):
      self.clients.append(client)

   def inform_client_leaves(self,client_leaved):
      for client in self.clients:
         if client.is_alive():
            client.inform("Client '{}' leaves".format(client_leaved.name))

   def run(self):
      while True:
         for thread in list(self.threads):
            if not thread.is_alive(): # client exited
               self.threads.remove(thread)
               self.inform_client_exits(thread)
         time.sleep(1)

所以初始代碼看起來像

mon = Monitoring()
mon.start()
while True:
        client = serverSocket.accept()
        t = ServerThread(client,"Client1")
        t.start()
        mon.add_client(t)

暫無
暫無

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

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