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()
注意:以上示例代碼中的服務器地址和端口需要根據實際情況進行修改。