python python通过TCP套接字发送/接收十六进制数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2442704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:39:29  来源:igfitidea点击:

python send/receive hex data via TCP socket

pythonsocketstcpaccess-control

提问by Mike

I have a ethenet access control device that is said to be able to communicate via TCP.
How can i send a pachet by entering the HEX data, since this is what i have from their manual (a standard format for the communication packets sent and received after each command)
Can you please show some example code or links to get started....

我有一个以太网访问控制设备,据说可以通过 TCP 进行通信。
我如何通过输入十六进制数据来发送小包,因为这是我从他们的手册中得到的(每个命令后发送和接收的通信数据包的标准格式)
你能否展示一些示例代码或链接以开始使用.. ..

standard return packet from the terminal
                               Size (bytes) 
BS (0x08) : ASCII Character         1
STX (0x02) : ASCII Character        1 
LENGTH : length from BS to ETX      4 
TID : system unique I.D.            1 
RESULT                              1 
DATA : returned parameter           N 
CHECKSUM : byte sum from BS to DATA 1 
ETX (0x03) : ASCII Character        1 
Standard command packet to the terminal  
                               Size (bytes) 
ACK (0x06) : ASCII Character         1 
STX (0x02) : ASCII Character         1 
LENGTH : length from ACK to ETX      4 
TID : system unique I.D. (ex: 1)     1 
COMMAND                              1 
Access Key(Optional)                 6 
DATA : command parameter             N 
CHECKSUM : byte sum from ACK to DATA 1 
ETX (0x03) : ASCII Character         1 

This packet starts from ACK. 
In this packet, multiple byte value must be started from MSB. 
For example, if length was 10, LENGTH is 0x00 0x00 0x00 0x0a. 

回答by Ignacio Vazquez-Abrams

Just encode the hex data in a string:

只需将十六进制数据编码为字符串:

'\x34\x82\xf6'

回答by Alex Martelli

I'd use struct.packto prepare the string of bytes to send, from the data you want to send. Be sure to start the packing format with >to mean you want big-endian ordering and standard sizes, since they document that so clearly!

我会使用struct.pack从您要发送的数据中准备要发送的字节串。一定要开始包装格式,>这意味着你想要大端排序和标准尺寸,因为它们记录得如此清楚!

So (I don't know what the "optional" means for the access key, I'll assume it means that the field can be all-zero bytes if you have no access key), if "data" is already a string of bytes and "command" a small unsigned integer for example, something like...:

所以(我不知道访问密钥的“可选”是什么意思,我假设这意味着如果您没有访问密钥,该字段可以是全零字节),如果“数据”已经是一串字节和“命令”一个小的无符号整数,例如……:

def stringfor(command, data, accesskey='##代码##'*6, tid=1):
  length = 16 + len(data)
  prefix = struct.pack('>BBIBB6s', 6, 2, length, tid, command, accesskey)
  checksum = sum(ord(c) for c in prefix) &0xFF
  return prefix + chr(checksum) + chr(3)