【问题标题】:Is python3.x library socketserver non-blocking?python3.x库socketserver是非阻塞的吗?
【发布时间】:2016-12-05 15:30:44
【问题描述】:

我正在阅读 socketserver.py 代码,我发现它正在使用 selectors.PollSelector(如果可用)。但是主套接字或 tcp 连接套接字上没有 setblocking(0)。有人可以解释为什么套接字设置为阻塞,因为它是默认套接字行为吗?

编辑

我做了一些测试,我什至应该更改标题...但是当您选择使用 select 时,套接字是否处于阻塞状态有关系吗?因为在这段代码中,sn-p,True/False对 setblocking 无效。

import sys
import socket
from time import sleep
import select

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('127.0.0.1',9999))
s.setblocking(1) # does it matter?
s.listen(10)
timeout=100
inp = [s]
out = []

def worker(client,num):
    print('Worker sending out',client,num)
    client.send( str(str(num)+'\n').encode('utf-8'))
    sleep(0.3)

server_client = {}
while True:
    print('in loop')
    try:
       inputready,outputready,_ = select.select(inp,out,[],timeout)
       for server in inputready:
           if server == s:
               print('accept',server)
               client, address = server.accept()
               client.setblocking(1) # does it matter?
               inp.append(client)
               out.append(client)
       for server in outputready:
           if server in server_client:
               server_client[server] += 1
           else:
               server_client[server] = 0
           worker(server,server_client[server])

    except BlockingIOError:
        print('ERR blocking')
        pass

【问题讨论】:

  • Sockets 被设置为阻塞通常是默认的,不仅仅是在socketserver 模块中,所以模块作者选择类似地实现默认值并不让我感到惊讶。然而,值得指出的是socketserversocket 模块都支持非阻塞模式。在套接字模块中可能更难识别,但要寻找“超时”。

标签: python sockets nonblocking socketserver


【解决方案1】:

简短的回答:

对于 select(),套接字/流/文件句柄是否阻塞没有区别。 仅读取或写入套接字,并且只有在没有数据可用时,行为才会有所不同。

说明(基于Linux):

  • 阻塞套接字上的读取调用将等待直到数据可用,如果套接字已关闭,则返回零字节。
  • 非阻塞套接字上的读取调用将返回数据(如果可用)或返回错误 EAGAIN。后者向上层库发出没有可用数据的信号。
  • 如果底层传输层的发送缓冲区已满,阻塞套接字上的写入调用可能会阻塞。
  • 非阻塞套接字上的写入调用将返回错误 EAGAIN,以防发送缓冲区已满,指示调用者稍后再试。

【讨论】:

    猜你喜欢
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2015-11-06
    • 2012-11-13
    • 2020-03-29
    • 2014-10-19
    相关资源
    最近更新 更多