非阻塞的Python套接字如何接收输入?

如果我有这个代码与一个解锁套接字有关,称为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)



慕侠2389804
浏览 92回答 1
1回答

呼啦一阵风

如果 是非阻塞的,则如果它以其他方式阻塞,它将引发。代码周围是否有 / 未显示?另一个选项用于确保在调用 之前读取要接收的数据。sockBlockingIOErrortryexceptselect.selectrecv假设相应服务器的示例:>>> from socket import *>>> s=socket()>>> s.connect(('localhost',5000))>>> s.setblocking(0)>>> s.recv(1024)Traceback (most recent call last):&nbsp; File "<stdin>", line 1, in <module>BlockingIOError: [WinError 10035] A non-blocking socket operation could not be completed immediately编辑:使用附加代码,仅在报告(数据准备读取)时调用,因此不应阻塞。它将返回数据或空字符串。后者表示套接字已关闭。recvsel.selectEVENT_READrecv
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python