首页 > 代码库 > IO多路复用之一

IO多路复用之一

1.socketserver的执行流程

技术分享

import socketserverclass MyClass(socketserver.BaseRequestHandler):    def handle(self):        passobj = socketserver.ThreadingTCPServer((127.0.0.1,9999),MyClass)obj.serve_forever()

 

IO多路复用SERVER端:

__author__ = alex#coding:utf-8import socketimport selectip_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__ = aleximport socketimport select#coding:utf-8ip_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()

 

IO多路复用之一