大话踩坑

selectors单线程ser端的坑

  1. 先贴段完善后的代码

import selectors
import socket,time

sel = selectors.DefaultSelector()

def accept(sock, mask):

conn, addr = sock.accept()  # Should be ready
# print('accepted:', conn, 'from:', addr)
conn.setblocking(0)
sel.register(conn, selectors.EVENT_READ, read)

def read(conn, mask):

    info = conn.recv(1024)    # Should be ready
    # print(">>>>info : ", info)
    if info:
        # print('echoing', repr(info), 'to', conn)
        # time.sleep(0.1)
        conn.send(info)     # Hope it won't block
        # print("in zhe 1----------------")
    else:
        print('closing', conn)
        sel.unregister(conn)
        conn.close()

sock = socket.socket()
sock.bind(('', 7677))
sock.listen(5)
sock.setblocking(0)
sel.register(sock, selectors.EVENT_READ, accept)
把刚才写写的sock注册到sel里,accept就是上个写的函数

print("waiting...")
while 1:
try: #这个地方不缩进,啥情况?
events = sel.select() ## 默认阻塞,
for key, mask in events:
callback = key.data ## 回调调用accept
callback(key.fileobj, mask) ## key.fileobj就是一个socket链接
except Exception as e:
print(e)
sel.unregister(key.fileobj)
key.fileobj.close()



IE内核好像不好用!

<font color=#0099f6 size=6>
最后试试字体颜色。
</font>