如果我有这个代码与一个解锁套接字有关,称为sock
recv_data = sock.recv(1024)
if recv_data:
data.outb += recv_data
else:
print('closing connection to', data.addr)
sel.unregister(sock)
sock.close()
究竟发生了什么?该语句与阻止和非阻止有何不同?如果程序不等待该语句完成,那么怎么会有价值呢?recv_data = sock.recv(1024)recv_data
编辑:完整的服务器代码:
import selectors
import socket
import types
host = "127.0.0.1"
port = 65432
def accept_wrapper(sock):
conn, addr = sock.accept()
print('accepted conneciton 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)
def service_connection(key, mask):
sock = key.fileobj
data = key.data
if mask & selectors.EVENT_READ:
recv_data = sock.recv(1024)
if recv_data:
data.outb += recv_data
else:
print('closing connection to', data.addr)
sel.unregister(sock)
sock.close()
if mask & selectors.EVENT_WRITE:
if data.outb:
print('echoing', repr(data.outb), 'to', data.addr)
sent = sock.send(data.outb)
data.outb = data.outb[sent:]
sel = selectors.DefaultSelector()
lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
lsock.bind((host, port))
lsock.listen()
print('listening on', (host, port))
lsock.setblocking(False)
sel.register(lsock, selectors.EVENT_READ, data=None)
while True:
events = sel.select(timeout=None)
for key, mask in events:
if key.data is None:
# From the listening socket
accept_wrapper(key.fileobj)
else:
# Client Socket
service_connection(key, mask)
呼啦一阵风
相关分类