一、服务端
import 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()