服务器套接字接受连接而不侦听。

huangapple go评论91阅读模式
英文:

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.

  1. import socket
  2. import threading
  3. ADDRESS = 'localhost', 10001
  4. EVENT = threading.Event()
  5. def server():
  6. with socket.create_server(ADDRESS) as _socket:
  7. #_socket.listen()
  8. EVENT.set()
  9. conn, _ = _socket.accept()
  10. with conn:
  11. print('Got client connection')
  12. (_server := threading.Thread(target=server)).start()
  13. EVENT.wait()
  14. with socket.socket() as _socket:
  15. _socket.connect(ADDRESS)
  16. _server.join()

Running this gives:

  1. 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. …

huangapple
  • 本文由 发表于 2023年6月8日 17:15:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76430327.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定