Python 3: 解析服务器消息(TCP)

Python 3: Parse Server message(TCP)

我使用套接字模块编写了一个客户端,现在我正在尝试使用以下代码解码从外部 TCP 服务器接收到的消息(我知道该包有一个 8 字节长 header,其中包含详细信息例如前 2 个字节的大小。在 Header 之后有一条错误消息,我正在尝试对其进行解码):

received = sock.recv(1024)
print ("Bytes Received: {}".format(received.decode()))

执行此操作时,我收到以下错误消息: UnicodeDecodeError: 'utf-8' 编解码器无法解码位置 0 中的字节 0xdc:无效的连续字节

当我尝试使用以下方法排除 header 时:

print ("Bytes Received: {}".format(received[9:].decode()))

我只得到一个空结果:

Bytes Received: 

也许您正在尝试解码“\x00”字节,例如:

>>> print('Output: ' + b'\x00'.decode())
Output: 
>>> 

无论如何,如果它是长8字节(UDP头是由8字节组成的,不是TCP)你应该写:

print ("Bytes Received: {}".format(received[8:].decode()))

如果你想使用 TCP 数据包,我建议你使用像 Scapy 这样的数据包操纵器:https://scapy.readthedocs.io/en/latest/installation.html