user_socket.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import socket
  2. import sys
  3. import threading
  4. import time
  5. import log
  6. import app
  7. class tcp_param:
  8. def __init__(self):
  9. self.host = 'localhost'
  10. self.port = 56926
  11. self.buffsize = 128
  12. self.rd_data = ''
  13. self.wr_data = ''
  14. self.wr_stat = False
  15. tcpserverParam = tcp_param()
  16. class socket_server(threading.Thread):
  17. def __init__(self, threadID, name, counter):
  18. threading.Thread.__init__(self)
  19. self.threadID = threadID
  20. self.name = name
  21. self.counter = counter
  22. self.user_var = app.user_var
  23. self.tcpserverParam = tcpserverParam
  24. # 获取本地主机名
  25. self.tcpserverParam.host = '127.0.0.1'
  26. self.BUFSIZE = self.tcpserverParam .buffsize
  27. # 创建 socket 对象
  28. self.serversocket = socket.socket(
  29. socket.AF_INET, socket.SOCK_STREAM)
  30. # 绑定端口号
  31. self.serversocket.bind((self.tcpserverParam.host, self.tcpserverParam.port))
  32. self.exit_stat = False
  33. self.exit_ok = False
  34. self.log_file = log.log_file
  35. self.log_print = log.log_file
  36. def exit(self):
  37. self.exit_stat = True
  38. def run(self):
  39. # 设置最大连接数,超过后排队
  40. self.serversocket.listen(5)
  41. while self.exit_stat == False:
  42. try:
  43. print('waiting for connection...')
  44. self.serversocket.settimeout(10)
  45. clientsocket, addr = self.serversocket.accept()
  46. print(addr)
  47. self.serversocket.settimeout(300)
  48. self.user_var.socket_conn_stat = True
  49. while self.exit_stat == False:
  50. if self.tcpserverParam.wr_stat == True:
  51. try:
  52. print('waiting for recv')
  53. msg = clientsocket.recv(18).decode("ascii")
  54. print(msg)
  55. if msg == 'TCP:Give me string':
  56. # time.sleep(2)
  57. size = clientsocket.send(self.tcpserverParam.wr_data.encode("ascii"))
  58. self.tcpserverParam.wr_stat = False
  59. self.log_print.logger.info('tcpsend={0}'.format(size), stack_info=True)
  60. except ConnectionResetError as e:
  61. self.log_file.logger.error('socket连接: {0}'.format(e), exc_info=True,
  62. stack_info=True)
  63. break
  64. except Exception as e:
  65. self.log_file.logger.error('socket未知异常: {0}'.format(e), exc_info=True, stack_info=True)
  66. break
  67. time.sleep(0.1)
  68. clientsocket.close()
  69. except socket.error as e:
  70. print("客户端断开!")
  71. except ConnectionResetError as e:
  72. self.log_file.logger.error('socket连接: {0}'.format(e), exc_info=True, stack_info=True)
  73. except Exception as e:
  74. self.log_file.logger.error('socket未知异常: {0}'.format(e), exc_info=True, stack_info=True)
  75. self.user_var.socket_conn_stat = False
  76. print("socket进程结束!")