import socket
import binascii
import struct
from SensingMonitoring_pb2 import Command, CommandNamesif __name__ == "__main__" : client = socket.socket( socket.AF_INET, socket.SOCK_STREAM) client.connect(( "192.168 .1 .100 ", 22295 )) command = Command( ) command.COMMANDID = 45678 command.COMMANDNAME = CommandNames.Value( 'AuthentcationRequest' ) command.AuthentcationRequest.VERSION = '1.0' command.AuthentcationRequest.DWBH = 'xxxxxxxxxx' command.AuthentcationRequest.LWRZBH = 'xxxxxxxxxxxxxxxxx' message = command.SerializeToString( ) lenght = struct.pack( '<I' , len( message)) .hex( ) message = binascii.hexlify( message) .decode( ) head = struct.pack( '<I' , 58250 ) .hex( ) client.send( bytes.fromhex( head + lenght + message))
# 接收响应数据data = client. recv ( 1024 ) data = binascii. hexlify ( data) . decode ( ) # 包头head = bytes. fromhex ( data[ : 8 ] ) head = struct . unpack ( '<I' , head) [ 0 ] # 包体长度length = bytes. fromhex ( data[ 8 : 16 ] ) length = struct . unpack ( '<I' , length) [ 0 ] # 包体, 十六进制字符串转换为对应的字节串body = bytes. fromhex ( data[ 16 : ] ) result = { "Flag" : head, "BodySize" : length, "Body" : body} command = Command ( ) command. ParseFromString ( body) print ( command) print ( command. AuthentcationResponse. INFO) client. close ( )