Python - 将uint8和uint16发送到socket

时间:2017-08-18 09:49:41

标签: python sockets

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

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

  • uint8版本号
  • uint8用于填充('保留')
  • a 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)

我一直使用此函数获取TypeErrors。这些会在len(message)r += message[...]或其他地方弹出。

我想知道是否有更好的方法可以做到这一点,或者如何解决这个问题,以便它确实有效?

更新:这里有一些完全错误跟踪。我尝试了几种不同的东西,因此这些错误痕迹可能已经变得无关紧要了。

Traceback (most recent call last):
  File "quick.py", line 47, in <module>
    header += numpy.uint8(VERSION_NUMBER)
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('S3') dtype('S3') dtype('S3')


header = numpy.array([VERSION_NUMBER * 255 + PADDING, len(greetData)], dtype=numpy.uint16)
Traceback (most recent call last):
  File "quick.py", line 48, in <module>
    print(header + greetData)
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('S22') dtype('S22') dtype('S22')


Traceback (most recent call last):
  File "quick.py", line 47, in <module>
    r = send(conn, numpy.uint8(VERSION_NUMBER))
  File "quick.py", line 13, in send
    while totalsent < len(message):
TypeError: object of type 'numpy.uint8' has no len()


Traceback (most recent call last):
  File "quick.py", line 47, in <module>
    r = send(conn, numpy.array([VERSION_NUMBER], dtype=numpy.uint8))
  File "quick.py", line 17, in send
    r += message[totalsent:]
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('S3') dtype('S3') dtype('S3')

1 个答案:

答案 0 :(得分:2)

在发送数据之前,您需要使用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(...)