zoukankan      html  css  js  c++  java
  • IO多路复用之一

    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()
  • 相关阅读:
    [CF1365D] Solve The Maze
    [CF478C] Table Decorations
    [CF466D] Increase Sequence
    [CF449D] Jzzhu and Numbers
    [CF507E] Breaking Good
    [CF337D] Book of Evil
    [CF1253E] Antenna Coverage
    VMware 在 Win10 下开机后死机的解决方案
    [CF1009F] Dominant Indices
    [CF1037E] Trips
  • 原文地址:https://www.cnblogs.com/python-study/p/5816335.html
Copyright © 2011-2022 走看看