Python 之socketserver模块实现多线程
2021-02-14 05:18
标签:pre ini ever rev request and port ctime div 一、服务端 Python 之socketserver模块实现多线程 标签:pre ini ever rev request and port ctime div 原文地址:https://www.cnblogs.com/yang-2018/p/12723952.htmlimport socketserver
import time
conn_poll = []
class MyServer(socketserver.BaseRequestHandler):
def handle(self):
print(‘... connected from {}‘.format(self.client_address))
conn_poll.append(self.client_address)
while True:
# request.recv 方法接收客户端发来的消息
data = self.request.recv(1024)
if data == ‘exit‘:
conn_poll.remove(self.client_address)
# 发送exit给客户端断开连接
self.request.sendall(data.encode(‘utf-8‘))
break
# request.sendall 方法发送消息给客户端
self.request.sendall(‘[{}] {}‘.format(time.ctime(), data.decode(‘utf-8‘)).encode(‘utf-8‘))
def finish(self):
print(‘finish‘)
if __name__ == ‘__main__‘:
s = socketserver.ThreadingTCPServer((‘‘, 12306), MyServer)
s.serve_forever()
文章标题:Python 之socketserver模块实现多线程
文章链接:http://soscw.com/index.php/essay/55098.html