英文:
Server socket accepts connection without listen
问题
对于服务器套接字,在接受连接之前通常需要调用 listen()
方法。然而,在这种情况下似乎并不需要。
运行这段代码后,会输出 "Got client connection",即使没有调用服务器套接字的 listen()
方法。如果调用 _socket.listen()
也不会改变行为。
这个现象可能是特定于Python的,或者我是否理解了某些基本概念?
英文:
It has always been my understanding that it is essential for a server socket to listen() before it can accept connections.
However, this appears not to be the case.
import socket
import threading
ADDRESS = 'localhost', 10001
EVENT = threading.Event()
def server():
with socket.create_server(ADDRESS) as _socket:
#_socket.listen()
EVENT.set()
conn, _ = _socket.accept()
with conn:
print('Got client connection')
(_server := threading.Thread(target=server)).start()
EVENT.wait()
with socket.socket() as _socket:
_socket.connect(ADDRESS)
_server.join()
Running this gives:
Got client connection
i.e., it worked without a call to listen() on the server socket.
There is no difference in behaviour if I invoke _socket.listen()
Is this something that's peculiar to Python or am I misunderstanding something fundamental?
Python 3.11.3 on MacOS 13.4
答案1
得分: 0
create_server
是一个方便的函数。它有一个 backlog 参数,并为您调用 listen
。
从文档中:
> … backlog 是传递给 socket.listen() 的队列大小;如果未指定,将选择一个默认的合理值。…
英文:
create_server
is a convenience function. It has a backlog parameter and calls listen
for you.
From the docs:
> … backlog is the queue size passed to socket.listen(); if not specified, a default reasonable value is chosen. …
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论