gpt4 book ai didi

python - TCP 连接中的 "backlog"是什么?

转载 作者:IT老高 更新时间:2023-10-28 20:31:04 26 4
gpt4 key购买 nike

在下面,您会看到一个 python 程序,它充当服务器监听对端口 9999 的连接请求:

# server.py 
import socket
import time

# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)

# get local machine name
host = socket.gethostname()

port = 9999

# bind to the port
serversocket.bind((host, port))

# queue up to 5 requests
serversocket.listen(5)

while True:
# establish a connection
clientsocket,addr = serversocket.accept()

print("Got a connection from %s" % str(addr))
currentTime = time.ctime(time.time()) + "\r\n"
clientsocket.send(currentTime.encode('ascii'))
clientsocket.close()

问题是socket.listen()方法(即5)的参数的作用是什么。

基于互联网上的教程:

The backlog argument specifies the maximum number of queued connections and should be at least 0; the maximum value is system-dependent (usually 5), the minimum value is forced to 0.

但是:

  1. 这些排队的连接是什么?
  2. 它对客户请求有什么影响吗? (我的意思是使用 socket.listen(5) 运行的服务器与使用 socket.listen(1) 运行的服务器在接受连接请求或接收数据?)
  3. 为什么最小值为零?不应该是至少1吗?
  4. 有首选值吗?
  5. 这个 backlog 是仅为 TCP 连接定义的,还是也适用于 UDP 和其他协议(protocol)?

最佳答案

注意:答案是在没有任何 Python 背景的情况下进行的,但是,这些问题与语言无关,需要回答。

What are these queued connections?

简单来说,积压参数指定队列将持有的挂起连接数。

当多个客户端连接到服务器时,服务器会将传入的请求保存在队列中。客户端排列在队列中,服务器在队列成员进行时一一处理它们的请求。这种连接的性质称为排队连接。

Does it make any difference for client requests? (I mean is the server that is running with socket.listen(5) different from the server that is running with socket.listen(1) in accepting connection requests or in receiving data?)

是的,这两种情况是不同的。第一种情况只允许将 5 个客户端安排到队列中;而在 backlog=1 的情况下,队列中只能保留 1 个连接,从而导致进一步的连接请求被丢弃!

Why is the minimum value zero? Shouldn't it be at least 1?

我不知道 Python,但是,as per this source ,在 C 中,积压参数 0 可能允许套接字接受连接,在这种情况下,监听队列的长度可以设置为实现定义的最小值。

Is there a preferred value?

这个问题没有明确的答案。我想说这取决于您的应用程序的性质,以及硬件配置和软件配置。同样,根据源代码,BackLog 默默地限制在 1 到 5 之间,包括 1 和 5(同样根据 C)。

Is this backlog defined for TCP connections only or does it apply for UDP and other protocols too?

没有。请注意,对于未连接的数据报套接字 (UDP),不需要 listen() 或 accept()。这是使用未连接的数据报套接字的好处之一!

但是,请记住,还有基于 TCP 的数据报套接字实现(称为 TCPDatagramSocket)也有积压参数。

关于python - TCP 连接中的 "backlog"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36594400/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com