码迷,mamicode.com
首页 > 编程语言 > 详细

python之selectors

时间:2018-10-04 10:49:25      阅读:375      评论:0      收藏:0      [点我收藏+]

标签:connect   leo   odi   tor   包装   nts   sock   部分   net   

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)

 

python之selectors

标签:connect   leo   odi   tor   包装   nts   sock   部分   net   

原文地址:https://www.cnblogs.com/xkxjy/p/9741087.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!