zoukankan      html  css  js  c++  java
  • python异步IO

    转:https://www.cnblogs.com/nulige/p/6297829.html

    select_module.py

    import selectors
    import socket
    
    sel = selectors.DefaultSelector()
    
    def accept(sock, mask):
        conn, addr = sock.accept()  # Should be ready
        print('accepted', conn, 'from', addr)
        conn.setblocking(False)  #设置成非阻塞
        sel.register(conn, selectors.EVENT_READ, read) #conn绑定的是read
    
    def read(conn, mask):
        try:
            data = conn.recv(1000)  # Should be ready
            if not data:
                raise Exception
            print('echoing', repr(data), 'to', conn)
            conn.send(data)  # Hope it won't block
        except Exception as e:
            print('closing', conn)
            sel.unregister(conn)  #解除注册
            conn.close()
    
    sock = socket.socket()
    sock.bind(('localhost', 8090))
    sock.listen(100)
    sock.setblocking(False)
    #注册
    sel.register(sock, selectors.EVENT_READ, accept)
    print("server....")
    
    while True:
        events = sel.select() #监听[sock,conn1,conn2]
        print("events",events)
        #拿到2个元素,一个key,一个mask
        for key, mask in events:
            # print("key",key)
            # print("mask",mask)
            callback = key.data  #绑定的是read函数
            # print("callback",callback)
            callback(key.fileobj, mask)  #key.fileobj=sock,conn1,conn2

    client.py

    import socket
    
    sk=socket.socket()
    
    sk.connect(("127.0.0.1",8090))
    while 1:
        inp=input(">>>")
        sk.send(inp.encode("utf8")) #发送内容
        data=sk.recv(1024)  #接收信息
        print(data.decode("utf8"))  #打印出来
  • 相关阅读:
    JS中return函数
    Java异常
    ssh框架整合之注解版
    ssh框架整合之xml版
    Struts之拦截器
    Struts入门初体验
    Hibernate关联查询 一对多双向关联
    Hibernate之hql
    Aop小列子
    深入.Net第二章总结
  • 原文地址:https://www.cnblogs.com/wangbin2188/p/13334877.html
Copyright © 2011-2022 走看看