socketserver.ThreadingTCPServer 实例。多线程支持多个客户端同时访问。支持客户端自动重连。
服务端:
# -*- coding:utf-8 -*- #!/usr/bin/env python import socketserver class myTCPhandler(socketserver.BaseRequestHandler): def handle(self): while True: self.data = self.request.recv(1024).decode('UTF-8', 'ignore').strip() if self.data : print(self.data) self.back_data =("response\""+self.data+"\":\n\tI am server").encode("utf8") self.request.sendall(self.back_data) else: print('wait request'); class myServer(): host = '127.0.0.1'; port = 80; def run(self): server = socketserver.ThreadingTCPServer((self.host,self.port), myTCPhandler) server.serve_forever() sh = myServer(); sh.run();
客户端:
# -*- coding:utf-8 -*- #!/usr/bin/env python import socket from time import sleep class Client: host = '127.0.0.1'; port = 80; bufsiz = 1024; addr = None; skt = None; def __init__(self, host = None, port = None): if host != None: self.host = host; if port != None: self.port = port; if self.addr == None: self.addr = (self.host, self.port); self.doConnection(); def doConnection(self): try: self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM); self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) #心跳 print(self.addr); self.skt.connect(self.addr); except: pass def run(self): while True: try: self.skt.sendall('i am clent1'.encode('utf-8')); data = self.skt.recv(self.bufsiz); print(data.decode('utf-8', 'ignore')); if not data: break; print(data.strip()); sleep(5) except socket.error: print('socket error, reconnection'); #自动重连 sleep(3); self.doConnection(); except: print('other error'); self.skt.close(); c = Client(); c.run();