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

python-IO多路复用的selectors模块

时间:2018-06-16 17:54:20      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:while   cto   selectors   not   leo   serve   enc   als   soc   

server端:

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)

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,,conn2]
    for key, mask in events:
        callback = key.data
        callback(key.fileobj, mask)

client端:

# 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"))

 

python-IO多路复用的selectors模块

标签:while   cto   selectors   not   leo   serve   enc   als   soc   

原文地址:https://www.cnblogs.com/benchdog/p/9190863.html

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