Python3.6+ 自带了 TCPServer 以便于更快编写 TCP 服务器,同时 Python 也提供了多线程的 Mixin 以提供多线程支持。
由于每个 TCPServer 只能服务于一个 TCP 连接,而 Python 的多线程 Mixin 并不限制最大连接数,所以可能会导致线程过度增长。
本文介绍一种简单的自制线程池方法的 Python TCP 服务器。
代码
settings.py
1BUF_SIZE = 1024
2SERVER_PORT = 8973
3THREAD_WORKERS_NUM = 10
server.py
1from socketserver import BaseRequestHandler, TCPServer
2from threading import Thread
3import settings
4import logging
5
6# 自定义的日志
7logging.basicConfig(
8 level=logging.INFO,
9 format='[%(levelname)s] %(asctime)s %(filename)s: %(message)s',
10 datefmt='%Y-%m-%d %A %H:%M:%S',
11 filename='socket.log',
12 filemode='a',
13)
14
15
16class ReceiveHandler(BaseRequestHandler):
17 def setup(self):
18 logging.info("Connect from: " + str(self.client_address))
19
20 def handle(self):
21 try:
22 while True:
23 msg = self.request.recv(settings.BUF_SIZE)
24 if msg:
25 # 接收处理
26 pass
27 else:
28 break
29 except Exception as e:
30 logging.warning('Exception is: ' + str(e))
31
32 def finish(self):
33 logging.info("Disconnect from: " + str(self.client_address))
34
35
36if __name__ == '__main__':
37 try:
38 logging.info("Start Server !")
39 socket_serve = TCPServer(('', settings.SERVER_PORT), ReceiveHandler)
40 for i in range(settings.THREAD_WORKERS_NUM):
41 t = Thread(target=socket_serve.serve_forever)
42 t.daemon = True
43 t.start()
44 socket_serve.serve_forever()
45 except KeyboardInterrupt:
46 socket_serve.shutdown()
47 logging.info("Stop Server !")
参考链接
版权声明:本文遵循 CC BY-SA 4.0 版权协议,转载请附上原文出处链接和本声明。
Copyright statement: This article follows the CC BY-SA 4.0 copyright agreement. For reprinting, please attach the original source link and this statement.