python中Socket.accept()的返回值是多少

2024-07-07 09:27:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python中的socket模块制作了一个简单的服务器和一个简单的客户机。

服务器:

# server.py
import socket

s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host, port))

s.listen(5)

while True:
    c, addr = s.accept()
    print 'Got connection from', addr
    c.send('Thank you for your connecting')
    c.close()

客户:

#client.py
import socket

s = socket.socket()

host = socket.socket()
port = 1234

s.connect((host, port))
print s.recv(1024)

我启动了服务器,然后启动了4个客户机,并在服务器控制台中得到如下输出:

Got connection from ('192.168.0.99', 49170)
Got connection from ('192.168.0.99', 49171)
Got connection from ('192.168.0.99', 49172)
Got connection from ('192.168.0.99', 49173)

元组的第二部分是什么?


Tags: 模块frompyimport服务器host客户机server
2条回答

引用自python documentation

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.

什么是address你可以在同一个文档中找到from words "Socket addresses are represented as follows"

^{} documentation

A pair (host, port) is used for the AF_INET address family, where host is a string representing either a hostname in Internet domain notation like 'daring.cwi.nl' or an IPv4 address like '100.50.200.5', and port is an integer.

所以第二个值是客户端用于连接的端口号。建立TCP/IP连接时,客户端选择一个传出端口号与服务器通信;服务器返回的数据包将被发送到该端口号。

相关问题 更多 >