1 回答

TA貢獻1735條經驗 獲得超5個贊
您需要將 connection, address = s.accept() 放在 while 循環之外,否則您的服務器每次都會等待新連接。
您接收數據的方式也有問題。connection.recv(4096)并非每次收到完整的“數據”消息時都會返回 0 到 4096 之間的任意字節數。要處理此問題,您可以在向您發送 json 之前發送一個標頭,指示應接收多少數據通過添加標頭,您將確保正確接收您發送的數據消息。
此示例中的標頭是一個四字節的 int,指示數據的大小。
服務器
import pickle
import socket
import struct
HEADER_SIZE = 4
HOST = "127.0.0.1"
PORT = 12000
def receive(nb_bytes, conn):
# Ensure that exactly the desired amount of bytes is received
received = bytearray()
while len(received) < nb_bytes:
received += conn.recv(nb_bytes - len(received))
return received
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
connection, address = s.accept()
while True:
# receive header
header = receive(HEADER_SIZE, connection)
data_size = struct.unpack(">i", header)[0]
# receive data
data = receive(data_size, connection)
print(pickle.loads(data))
客戶
import socket
import pickle
import math
HEADER_SIZE = 4
HOST = "127.0.0.1"
PORT = 12000
den = 20
rad = 100
theta = math.tau / den
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((HOST, PORT)) #connect to server
for step in range(1000):
i = step%den
x = math.cos(i*theta) * rad
y = math.sin(i*theta) * rad
data = pickle.dumps((x, y), protocol=0)
# compute header by taking the byte representation of the int
header = len(data).to_bytes(HEADER_SIZE, byteorder ='big')
sock.sendall(header + data)
希望能幫助到你
添加回答
舉報