簡體   English   中英

Python-將uint8和uint16發送到套接字

[英]Python - send uint8 and uint16 to socket

我正在嘗試使用python腳本向Java服務器發送一些數據。 我在python中使用套接字模塊來發送和接收數據。

發送數據時,需要指定一個帶有數據長度的標頭。 標題如下:

  • 一個uint8作為版本號
  • 用於填充的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)

我通過此功能不斷收到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')

您需要在發送數據之前使用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(...)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM