如何通过套接字发送数组,然后在python中获取每个项

2024-09-30 08:22:01 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我的服务器.py以及客户端.py. 所以我想打印数组中用新行分隔的每个项。 服务器.py以下内容:

import socket

listener = socket.socket()
listener.bind(("",12345))
listener.listen()

while 1:
    conn = listener.accept()
    sock = conn[0]

    encoded_message = sock.recv(2048)
    while len(encoded_message) > 0:
    message += encoded_message.decode() + "\n"
    encoded_message = sock.recv(2048)

print(message)

encoded_message = message.encode()
sock.send(encoded_message)
sock.shutdown(1)

sock.close()

在客户端.py以下内容:

^{pr2}$

但我总是

A123 45L65 78E486D4 1 0
E1.0
S1.0
S0 2 -945 1689 -950 230 -25 1 -1e-15
Not a number
S0 2 -945 1689 -950 230 -25 1 0
S0 2 -945 1689 -950 230 G 1 1e-15

似乎前三个项目总是在一起,其余的工作都很好。我想把它们分开打印出来。我会很感激你的帮助。谢谢。 预期产量:

A123 45
L65 78
E486
D4 1 0
E1.0
S1.0
S0 2 -945 1689 -950 230 -25 1 -1e-15
Not a number
S0 2 -945 1689 -950 230 -25 1 0
S0 2 -945 1689 -950 230 G 1 1e-15

Tags: py服务器客户端numbermessagenotsocketconn
1条回答
网友
1楼 · 发布于 2024-09-30 08:22:01

每一条消息的大小不同,所以我认为实现这一点的最佳方法是使用XML、JSON等序列化进行结构化通信

如果不希望使用序列化,则可以在每次发送数据时使用开始和结束标记或唯一符号,如管道“|”。 因此,在服务器代码中,您应该连接所有消息,并最终将最终内容拆分为一个列表。在

separator = "|".encode()
for c in testing_strings:
    encoded_message = c.encode()
    sock.send(separator)
    sock.send(encoded_message)

我写了一个类似问题的答案,你可以看到:

{a1}

我希望这对你有帮助。在

相关问题 更多 >

    热门问题