Python将uint8和uint16发送到s

2024-04-26 02:24:15 发布

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

我试图用python脚本将一些数据发送到java服务器。我使用python中的socket模块来发送和接收数据。在

当我发送数据时,我需要指定一个包含datalength的头。标题如下:

  • 版本号的uint8
  • 填充('reserved')的uint8
  • 一个uint16,表示发送的数据的长度

总共32位。在

我可以使用numpy创建具有特定数据类型的数组,但问题是通过套接字发送这些数据。我使用以下函数发送数据:

def send(socket, message):
    r = b''

    totalsent = 0
    # as long as not everything has been sent ...
    while totalsent < len(message):
        # send it ; sent = actual sent data
        sent = socket.send(message[totalsent:])

        r += message[totalsent:]

        # nothing sent? -> something wrong
        if sent == 0:
            raise RuntimeError("socket connection broken")

        # update total sent
        totalsent = totalsent + sent

    return r

message = (something_with_numpy(VERSION_NUMBER, PADDING, len(data)))
send(socket, message)

我一直在用这个函数打字。这些会在len(message)r += message[...]或其他地方弹出。在

我想知道是否有更好的方法来完成这个任务,或者如何修复这个问题,使之生效?在


更新:以下是一些精确的错误跟踪。我尝试了几种不同的方法,所以这些错误痕迹可能已经变得无关紧要了。在

^{pr2}$

Tags: 数据方法函数numpysendmessagedatalen
1条回答
网友
1楼 · 发布于 2024-04-26 02:24:15

在发送数据之前,您需要使用struct模块格式化头部。在

import struct

def send_message(socket, message):
    length = len(message)
    version = 0  # TODO: Is this correct?
    reserved = 0  # TODO: Is this correct?
    header = struct.pack('!BBH', version, reserved, length)
    message = header + message  # So we can use the same loop w/ error checking
    while ...:
        socket.send(...)

相关问题 更多 >