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

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

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

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:

确定