我是一个套接字领域的初学者,最近尝试用它来创建一个终端聊天应用程序。我仍然很难理解setblocking和select函数
“这是我从我正在阅读的网站上获取的代码,如果数据中没有任何内容,这意味着套接字已断开连接,请解释什么影响服务器或客户端的setblocking。我在某个地方读到过setblocking允许在完全未收到数据的情况下继续,我对解释不太满意。请用简单的词解释
import select
import socket
import sys
import Queue
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)
server_address = ('localhost', 10000)
server.bind(server_address)
server.listen(5)
inputs = [ server ]
outputs = [ ]
message_queues = {}
while inputs:
readable, writable, exceptional = select.select(inputs, outputs, inputs)
for s in readable:
if s is server:
connection, client_address = s.accept()
connection.setblocking(0)
inputs.append(connection)
message_queues[connection] = Queue.Queue()
else:
data = s.recv(1024)
if data:
message_queues[s].put(data)
if s not in outputs:
outputs.append(s)
else:
if s in outputs:
outputs.remove(s)
inputs.remove(s)
s.close()
recv()的POSIX规范说明:
在Python接口中,返回值0对应于长度为0的返回缓冲区。e在
data
中什么都没有setblocking(0)
将套接字设置为非阻塞,即。e。如果e。g。accept()
或recv()
不能立即完成,操作失败而不是阻塞直到完成。在给定的代码中,这几乎不可能发生,因为操作在可能之前没有尝试过(由于使用了select()
)。但是,这个例子不好,因为它在select()
参数中包含了output
,这导致了一个繁忙的循环,因为output
大部分时间是可写的相关问题 更多 >
编程相关推荐