comCation.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import threading
  2. import time
  3. class ComCationServer(threading.Thread):
  4. def __init__(self, client, userList):
  5. threading.Thread.__init__(self)
  6. self.setDaemon(True)
  7. self.client = client
  8. self.userList = userList
  9. def __del__(self):
  10. if self.client in self.userList:
  11. self.userList.remove(self.client)
  12. self.client.close()
  13. def run(self):
  14. db = str.encode('服务器收到')
  15. while True:
  16. try:
  17. msg = self.client.recv(1024)
  18. if not msg:
  19. self.userList.remove(self.client)
  20. self.client.close()
  21. print('clinet exit1:', len(self.userList))
  22. break
  23. # 去除自己,客户端大于1才转发
  24. for c in self.userList:
  25. if c != self.client:
  26. # print('转发')
  27. c.sendall(msg)
  28. # self.client.sendall(db)
  29. print('客户信息', msg, time.ctime())
  30. time.sleep(1)
  31. except:
  32. self.userList.remove(self.client)
  33. self.client.close()
  34. print('client exit2:', len(self.userList))
  35. break