1.socketserver的执行流程
import socketserver class MyClass(socketserver.BaseRequestHandler): def handle(self): pass obj = socketserver.ThreadingTCPServer(('127.0.0.1',9999),MyClass) obj.serve_forever()
IO多路复用SERVER端:
__author__ = 'alex' #coding:utf-8 import socket import select ip_port = ('127.0.0.1',9999) sk = socket.socket() sk.bind(ip_port) sk.listen(5) inputs = [sk,] outputs = [] while True: rlist,wlist,e = select.select(inputs,outputs,[],2) print (len(inputs),len(rlist),len(wlist),len(outputs)) for r in rlist: if r == sk: conn,addr = r.accept() inputs.append(conn) conn.sendall(bytes('hello','utf8')) else: try: ret = r.recv(1024) if not ret: raise Exception("断开异常连接") else: outputs.append(r) except Exception: inputs.remove(r) for w in wlist: w.sendall(bytes("response","utf8")) outputs.remove(w)
IO多路复用CLIENT端:
__author__ = 'alex' import socket import select #coding:utf-8 ip_port = ('127.0.0.1',9999) sk = socket.socket() sk.connect(ip_port) data = sk.recv(1024) print (str(data,'utf8')) while True: inp = input(">>>>>>>>") sk.sendall(bytes(inp,encoding='utf8')) print (sk.recv(1024)) sk.close()