简体   繁体   English

简单的多线程服务器客户端程序

[英]Simple multithreaded Server Client Program

I have a multithreaded server and client programs for a simple game.我有一个用于简单游戏的多线程服务器和客户端程序。 Whenever a client force exits the game, I try to catch the exception with a try catch "except BrokenPipeError" and inform the other players.每当客户端退出游戏时,我都会尝试使用 try catch "except BrokenPipeError" 来捕获异常并通知其他玩家。 I also want to end the exited client thread;我也想结束退出的客户端线程; however, I take input such as this:但是,我接受这样的输入:

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

I tried to use a threading event with stop() function;我尝试使用带有 stop() 函数的线程事件; however, I believe I can not use a .join statement to exit the thread because of the way I take input.但是,我相信我不能使用 .join 语句退出线程,因为我接受输入的方式。 How should I end the force exited client.我应该如何结束强制退出客户端。 I know that multiprocessing library has a terminate function but I am also required to use the threading library.我知道多处理库有一个终止函数,但我也需要使用线程库。 I tried os_exit(1) but I believe this command kills the entire process.我试过 os_exit(1) 但我相信这个命令会杀死整个过程。 What is the standard exit process for programs such as this?此类程序的标准退出流程是什么?

First of all join() do nothing else but waits for thread to stop.首先join()除了等待线程停止之外什么都不做。 Thread stops when it reaches end of threaded subroutine.线程到达线程子程序结束时停止。 For example例如

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

If you want to inform other clients that someone leaves, i would make another monitoring thread如果您想通知其他客户有人离开了,我会制作另一个监控线程

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)

So the initial code would looks like所以初始代码看起来像

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