使用 pickle 将数据从服务器发送到客户端

问题描述 投票:0回答:1

我有一台服务器,它使用 pickle 从客户端获取一些数据,对其进行处理并尝试将数据发送回客户端。从客户端接收数据没问题,但是当尝试将其发送回客户端时,我收到错误:

Bad file descriptor
.

客户:

aggregated_ndarrays: List[np.ndarray] = parameters_to_ndarrays(aggregated_parameters)
# send the aggregated weights to the central server together with the number of   training-examples
print("Attempting server connection")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1", 8088))
transmit(sock, (aggregated_ndarrays, n_examples_fit))
# get back the new weights from the central server
with sock, sock.makefile('rb') as rfile:
    print(rfile.read())
    new_aggregated_parameters = pickle.load(rfile)
# serialize them and return them
new_aggregated_parameters = ndarrays_to_parameters(new_aggregated_parameters)

服务器:

import socket
import pickle

NUM_CLIENTS = 1

def central_server():
    connections = []
    weights = []
    number = []
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('localhost', 8088))
    s.listen()
    for c in range(0, NUM_CLIENTS):
        client, addr = s.accept()
        connections.append(client)
        print(f'{addr}: connected')
        with client, client.makefile('rb') as rfile:
            while True:
                try:
                    data = pickle.load(rfile)
                    weights.append(data[0])
                    number.append(data[1])
                    break
                except EOFError:  # Throws exception if incomplete or socket closed
                    break
        # Average the results
        print(weights)
        prior_weights = list(
            zip(weights[0]))
        new_weights = [
            sum(x * y for x, y in zip(prior_weights[i], [number[0]])) / sum(
                [number[0]]) for i in range(len(prior_weights))]
        for client in connections:
            transmit(client, new_weights)

我的假设是套接字预先关闭,因此不再与客户端建立连接。如何在不更改数据类型的情况下将数据发送回客户端?有没有更方便的协议来解决这个问题?

我正在使用 python3.10

python sockets network-programming pickle
1个回答
0
投票

退出

with
with client, client.makefile('rb') as rfile:
关闭
client
套接字和
rfile
包装器。在
# Average the results
块内缩进
with
下的代码,使
client
保持打开状态。

© www.soinside.com 2019 - 2024. All rights reserved.