11.4.2 带超时的非阻塞I/O
select()还可以有可选的第四个参数——如果没有活动通道,它在停止监视之前会等待一定时间,这个参数就是这里等待的秒数。通过使用一个超时值,可以让主程序在一个更大的处理循环中调用select(),在检查网络输入的间隙完成其他动作。
超过这个超时期限时,select()会返回3个空列表。如果要更新前面的服务器示例来使用一个超时值,则需要向select()调用增加一个额外的参数,并在select()返回后处理空列表。
import select
import socket
import sys
import queue
# Create a TCP/IP socket.
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.setblocking(0)
# Bind the socket to the port.
server_address = ('localhost',10000)
print('starting up on {} port {}'.format(*server_address),
file=sys.stderr)
server.bind(server_address)
# Listen for incoming connections.
server.listen(5)
# select()的参数是3个列表,包含要监视的通信通道。首先检查第一个对象列表中的对象
# 以得到要读取的数据。第二个列表中包含的对象将接收发出的数据(如果缓冲区有空间),
# 第三个列表包含哪些可能有错误的对象(通常是输入和输出通道对象的组合)。下一步是
# 建立这些列表,其中包含要传至select()的输入源和输出目标。
# Sockets from which we expect to read
inputs = [server]
# Sockets to which we expect to write
outputs = []
timeout = 0.1
# 由服务器主循环向这些列表增加或删除连接。由于这个服务器版本在发送数据之前要等待
# 套接字变为可写(而不是立即发送应答),所以每个输出连接都需要一个队列作为通过这个
# 套接字发送的数据的缓冲区。
# Outgoing message queues (socket:Queue)
message_queues = {}
# 服务器程序的主要部分会循环调用select()来阻塞并等待网络活动。
while inputs:
# Wait for at least one of the sockets to be
# ready for processing.
print('waiting for the next event',file=sys.stderr)
readable,writable,exceptional = select.select(inputs,
outputs,
inputs,
timeout)
if not (readable or writable or exceptional):
print(' timed out, do some other work here',
file=sys.stderr)
continue
# select()返回3个新列表,包含所传入列表内容的子集。readable雷彪中的所有套接字
# 会缓存到来的数据,可供读取。writable列表中所有套接字的缓冲区中有自由空间,
# 可以写入数据。exceptional中返回的套接字都有一个错误("异常条件"的具体定义取决
# 于平台)。
# “可读”套接字表示3种可能的情况。如果套接字是主“服务器”套接字,即用来监听
# 连接的套接字,那么“可读”条件就意味着它已经准备就绪,可以接受另一个入站连接
# 除了将新连接增加到要监视的输入列表,这里还会将客户套接字设置为非阻塞。
# Handle inputs
for s in readable:
if s is server:
# A "readable" socket is ready to accept a connection.
connection,client_address = s.accept()
print(' connection from',client_address,
file=sys.stderr)
connection.setblocking(0)
inputs.append(connection)
# Give the connection a queue for data
# we want to send.
message_queues[connection] = queue.Queue()
# 下一种情况是与一个已发送数据的客户建立连接。数据用recv()读取,然后放置在
# 队列中,以便通过套接字发送并返回给客户。
else:
data = s.recv(1024)
if data:
# A readable client socket has data.
print(' received {!r} from {}'.format(
data,s.getpeername()),file=sys.stderr,
)
message_queues[s].put(data)
# Add output channel for response.
if s not in outputs:
outputs.append(s)
# 如果一个可读套接字未从recv()返回数据,那么说明这个套接字来自已经断开连接
# 的客户,此时可以关闭流。
else:
# Interpret empty result as closed connection.
print(' closing',client_address,
file=sys.stderr)
# Stop listening for input on the connection.
if s in outputs:
outputs.remove(s)
inputs.remove(s)
s.close()
# Remove message queue.
del message_queues[s]
# 对于可写连接,情况要少一些。如果一个连接的相应队列中有数据,那么就发送下
# 一个消息。否则,将这个连接从输出连接列表中删除,这样下一次循环时,select()
# 不再指示这个套接字已准备好发送数据。
# Handle outputs.
for s in writable:
try:
next_msg = message_queues[s].get_nowait()
except queue.Empty:
# No messages waiting, so stop checking
# for writability.
print(' ',s.getpeername(),'queue empty',
file=sys.stderr)
outputs.remove(s)
else:
print(' sending {!r} to {}'.format(next_msg,s.getpeername()),
file=sys.stderr)
s.send(next_msg)
# 最后一种情况,exceptional列表中的套接字会关闭。
# Handle "exceptional conditions."
for s in exceptional:
print('exception condition on',s.getpeername(),
file=sys.stderr)
# Stop listening for input on the connection.
inputs.remove(s)
if s in outputs:
outputs.remove(s)
s.close()
# Remove message queue.
del message_queues[s]
客户程序的这个“慢”版本会在发送各个消息之后暂停,模拟传输中的时延或其他延迟。
import socket
import sys
import time
# Create a TCP/IP socket.
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening.
server_address = ('localhost',10000)
print('connecting to {} port {}'.format(*server_address),
file=sys.stderr)
sock.connect(server_address)
time.sleep(1)
messages = [
'Part one of the message.',
'Part two of the message.',
]
amount_expected = len(''.join(messages))
try:
# Send data.
for message in messages:
data = message.encode()
print('sending {!r}'.format(data),file=sys.stderr)
sock.sendall(data)
time.sleep(1.5)
# Look for the response.
amount_received = 0
while amount_received < amount_expected:
data = sock.recv(16)
amount_received += len(data)
print('received {!r}'.format(data),file=sys.stderr)
finally:
print('closing socket',file=sys.stderr)
sock.close()
运行这个新服务器和慢客户,服务器会生成以下结果:
以下是客户输出: