import socket
import selectors
import types
host, port = "127.0.0.1", 65432
sel = selectors.DefaultSelector()
def accept_wrapper(sock):
conn, addr = sock.accept() # Should be ready to read
print("accepted connection from", addr)
conn.setblocking(False)
data = types.SimpleNamespace(addr=addr, inb=b"", outb=b"")
events = selectors.EVENT_READ | selectors.EVENT_WRITE
sel.register(conn, events, data=data) # register for conn, for later communication
def service_connection(key, mask):
conn, data = key.fileobj, key.data # conn socket actually
if mask & selectors.EVENT_READ:
recv_data = conn.recv(1024) # Should be ready to read
if recv_data:
data.outb += recv_data
else:
print("closing connection to", data.addr)
sel.unregister(conn)
conn.close()
if mask & selectors.EVENT_WRITE:
if data.outb:
print("echoing", repr(data.outb), "to", data.addr)
sent = conn.send(data.outb) # Should be ready to write
data.outb = data.outb[sent:]
lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
lsock.bind((host, port))
lsock.listen()
print("listening on", (host, port))
lsock.setblocking(False)
# later listening operation committed to sel
# server was registered without data
sel.register(lsock, selectors.EVENT_READ, data=None)
try:
while True:
events = sel.select(timeout=None) # when read operation is allowed
for key, mask in events:
if key.data is None: # now we know it is server here, ready to accept connection
accept_wrapper(key.fileobj)
else:
service_connection(key, mask) # conn here, services should be offered
except KeyboardInterrupt:
print("caught keyboard interrupt, exiting")
finally:
sel.close()
server.py
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 首先执行 pip install pymysql。 然后在 项目 目录下 __init__.py 中添加如下代码:...
- django-admin是用于管理Django的命令行工具集,当我们成功安装Django后,在操作系统中就会有这个...
- 原文: http://zengrong.net/post/2192.htm 本站文章除注明转载外,均为本站原创或...
- 任务宝对我来说是一个完全陌生的领域,经过一次训练营的学习,对海报裂变的逻辑有了一定的认知。 1.锁定自己的目标客户...