1 回答

TA貢獻(xiàn)1735條經(jīng)驗(yàn) 獲得超5個(gè)贊
您需要將 connection, address = s.accept() 放在 while 循環(huán)之外,否則您的服務(wù)器每次都會(huì)等待新連接。
您接收數(shù)據(jù)的方式也有問題。connection.recv(4096)并非每次收到完整的“數(shù)據(jù)”消息時(shí)都會(huì)返回 0 到 4096 之間的任意字節(jié)數(shù)。要處理此問題,您可以在向您發(fā)送 json 之前發(fā)送一個(gè)標(biāo)頭,指示應(yīng)接收多少數(shù)據(jù)通過添加標(biāo)頭,您將確保正確接收您發(fā)送的數(shù)據(jù)消息。
此示例中的標(biāo)頭是一個(gè)四字節(jié)的 int,指示數(shù)據(jù)的大小。
服務(wù)器
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)
希望能幫助到你
添加回答
舉報(bào)