Python Socket客户端接收数据的方法有两种:
示例代码:
import socket
# 创建Socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
server_address = ('127.0.0.1', 8888)
client_socket.connect(server_address)
# 接收数据
data = client_socket.recv(1024)
print(data.decode())
# 关闭Socket连接
client_socket.close()
示例代码:
import socket
# 创建Socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定本地地址和端口
client_address = ('127.0.0.1', 8888)
client_socket.bind(client_address)
# 接收数据
data, server_address = client_socket.recvfrom(1024)
print('接收到来自{}的数据:{}'.format(server_address, data.decode()))
# 关闭Socket连接
client_socket.close()
注意:以上示例代码中的服务器地址和端口需要根据实际情况进行修改。