python3.x库socketserver是非阻塞的吗?

python3.x库socketserver是非阻塞的吗?,python,sockets,nonblocking,socketserver,Python,Sockets,Nonblocking,Socketserver,我正在阅读socketserver.py代码,发现它正在使用selectors.PollSelector(如果可用)。但主套接字或tcp连接套接字上没有锁定(0)。有人能解释为什么套接字设置为阻塞,因为这是默认的套接字行为吗 编辑 我做了一些测试,甚至应该更改标题……但当您选择使用select时,套接字是否处于阻塞状态有关系吗?因为在这个代码段中,setblocking上的True/False无效 import sys import socket from time import sleep i

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

编辑

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

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
简单的回答是: 对于select(),套接字/流/文件句柄是否阻塞没有区别。 只有从套接字读取或写入数据,并且只有在没有数据可用时,行为才会有所不同

说明(基于Linux):
  • 阻塞套接字上的读取调用将等待数据可用,如果套接字已关闭,则返回零字节
  • 非阻塞套接字上的读取调用将返回数据(如果可用)或返回引擎盖下的错误EAGAIN。后者向上层库发出没有可用数据的信号
  • 如果底层传输层的发送缓冲区已满,则对阻塞套接字的写调用可能会阻塞
  • 如果发送缓冲区已满,非阻塞套接字上的写调用将返回错误EAGAIN,通知调用方稍后重试
Sockets设置为block通常是默认值,而不仅仅是在模块中,因此模块作者选择以类似方式实现默认值并不奇怪。但是,值得指出的是,
socketserver
和模块都支持非阻塞模式。在套接字模块中可能更难识别,但要查找“超时”。