python 套接字中的 conn, addr = s.accept() 是什么?

What is `conn, addr = s.accept()` in python socket?

我搜索了文档和教程,但没有人谈论这个,例如这是服务器脚本

import socket
 
server = socket.socket()
print("socket created")

server.bind(("localhost", 9999))
server.listen(3)
print("waiting for connection")

while True:
    client, addr = server.accept()
    print(client)
    print(addr)
    
    name = client.recv(1024).decode()
    print("connected with", addr, client, name)
    
    client.send(b"welcome bro")       
    client.close()

 

当打印 client 时,我得到这个:

proto=0, laddr=('127.0.0.1', 9999), raddr=('127.0.0.1', 36182)

addr变量:

('127.0.0.1', 36182)

为什么这两个变量定义为一个,得到两个不同的输出?

幕后逻辑是什么?

脚本本身不会回答这个问题,但是,我假设 laddr=('127.0.0.1', 9999) 是服务器端应用程序的监听地址。这就是建立联系的地方。 raddr 是请求来自的连接端口。当您使用服务器侦听端口时,客户端使用任何大于 1024 的非保留端口连接到服务器,这完全是随机的,只要它在客户端应用程序中定义即可。

因此,对于一个已建立的连接,您必须使用不同的连接点。一个端口和地址作为发送方(描述为 raddr),一个作为接收方(此处描述为 laddr - 用于监听)

这基本上就是任何与 TCP 相关的连接背后的逻辑。

来自documentation of the socked module

socket.accept()

Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection.

accept() 函数 returns 连接到您的 TCP 服务器的套接字描述符。在这种情况下,它 returns 一个对象元组。

第一个参数 conn 是一个套接字对象,您可以使用它向已连接的客户端发送数据或从中接收数据。

第二个参数,addr,包含连接的客户端的地址信息(例如,IP地址和远程部分)。