我很难理解python中socket编程的代码

2024-04-23 20:42:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个套接字领域的初学者,最近尝试用它来创建一个终端聊天应用程序。我仍然很难理解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()


Tags: inimportmessagedataifserverqueueaddress
1条回答
网友
1楼 · 发布于 2024-04-23 20:42:24

if there is nothing in data, how does it mean that the socket has been disconnected

recv()的POSIX规范说明:

Upon successful completion, recv() shall return the length of the message in bytes. If no messages are available to be received and the peer has performed an orderly shutdown, recv() shall return 0. …

在Python接口中,返回值0对应于长度为0的返回缓冲区。edata中什么都没有

what affect the setblocking in the server or the client does.

setblocking(0)将套接字设置为非阻塞,即。e。如果e。g。accept()recv()不能立即完成,操作失败而不是阻塞直到完成。在给定的代码中,这几乎不可能发生,因为操作在可能之前没有尝试过(由于使用了select())。但是,这个例子不好,因为它在select()参数中包含了output,这导致了一个繁忙的循环,因为output大部分时间是可写的

相关问题 更多 >