如果我有这个代码与一个解锁套接字有关,称为sockrecv_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 selectorsimport socketimport typeshost = "127.0.0.1"port = 65432def 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)
1 回答
呼啦一阵风
TA贡献1802条经验 获得超6个赞
如果 是非阻塞的,则如果它以其他方式阻塞,它将引发。代码周围是否有 / 未显示?另一个选项用于确保在调用 之前读取要接收的数据。sockBlockingIOErrortryexceptselect.selectrecv
假设相应服务器的示例:
>>> from socket import *
>>> s=socket()
>>> s.connect(('localhost',5000))
>>> s.setblocking(0)
>>> s.recv(1024)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
BlockingIOError: [WinError 10035] A non-blocking socket operation could not be completed immediately
编辑:
使用附加代码,仅在报告(数据准备读取)时调用,因此不应阻塞。它将返回数据或空字符串。后者表示套接字已关闭。recvsel.selectEVENT_READrecv
添加回答
举报
0/150
提交
取消