python之selectors

发布时间:2019-03-15 23:30:31编辑:auto阅读(2679)

    selectors是select模块的包装器,ptython文档建议大部分情况使用selectors而不是直接使用selectors

    样例代码如下

    # -*- coding: utf-8 -*-
    __author__ = 'fc'
    
    import selectors
    import socket
    import time
    
    def accept(sock:socket.socket, mask):
        conn, addr = sock.accept()
        print('client', addr, 'connected')
        conn.setblocking(False)
        sel.register(conn, selectors.EVENT_READ, oper)
    
    def oper(sock:socket.socket, mask):
        if selectors.EVENT_READ & mask:
            print('ready to read')
            data = sock.recv(1024)
            if not data:
                print('client', sock.getpeername(), 'disconnnected')
                sel.unregister(sock)
                sock.close()
            else:
                print('received: ', data)
                sel.modify(sock, selectors.EVENT_WRITE, oper)
        elif selectors.EVENT_WRITE & mask:
            print('ready to write')
            msg = b'hello, friend'
            sock.send(msg)
            print('send: ', msg)
            sel.modify(sock, selectors.EVENT_READ, oper)
    
    
    sel = selectors.DefaultSelector()
    print(sel)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
    sock.bind(('', 60001))
    sock.listen(5)
    sock.setblocking(False)
    sel.register(sock, selectors.EVENT_READ, accept)
    
    while True:
        events = sel.select(10)
        if not events:
            print('timeout', time.strftime('%Y-%m-%d %H:%M:%S'))
        for key, mask in events:
            callback = key.data
            callback(key.fileobj, mask)
    

     

关键字