码迷,mamicode.com
首页 > 其他好文 > 详细

听说这里的markdown好用?特意来试试!

时间:2018-02-26 13:26:14      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:学习随笔

大话踩坑

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:

print(key)

        # print("mask",mask)
        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=4>最后试试字体颜色。</font>

听说这里的markdown好用?特意来试试!

标签:学习随笔

原文地址:http://blog.51cto.com/13160196/2073014

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