python 的 socket 如何不调用 listen 方法,就只能发送数据,而不能接收数据或接受连接请求?
我感觉不对啊,不 listen,也可以收和发数据呀,比如客户端的 socket,不用调用 listen,也是可读可写呀
回答:
看看下面的例子你就明白了:
服务器端:
import socketserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345))
server_socket.listen(5)
print("Server is listening for incoming connections...")
client_socket, client_address = server_socket.accept()
print(f"Connected to client at {client_address}")
received_data = client_socket.recv(1024).decode()
print(f"Received data from client: {received_data}")
response_data = "Hello from the server!"
client_socket.send(response_data.encode())
client_socket.close()
server_socket.close()
客户端:
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 12345))
message = "Hello from the client!"
client_socket.send(message.encode())
received_data = client_socket.recv(1024).decode()
print(f"Received data from server: {received_data}")
client_socket.close()
回答:
listen
是给服务端用来被动监听客户端用的啊,然后需要搭配accept
去使用。socket.listen() 让socket处于被动模式, 等待传入的连接和请求。如果不调用listen(),socket将无法接受传入的连接。
而且官网对这个api的解释就是这样。
socket.listen([backlog])
Enable a server to accept connections
. If backlog is specified, it must be at least 0 (if it is lower, it is set to 0); it specifies the number of unaccepted connections that the system will allow before refusing new connections. If not specified, a default reasonable value is chosen.
以上是 python 的 socket 如何不调用 listen 方法,就只能发送数据,而不能接收数据或接受连接请求? 的全部内容, 来源链接: utcz.com/p/938870.html