Python3 套接字客户端发送和接收十六进制字符串
Python3 socket client to send and receive hex string
我卡在这个套接字客户端Python3代码:
import socket
import codecs
def Main():
host = '127.0.0.2'
port = 502
mySocket = socket.socket()
mySocket.connect((host,port))
message = codecs.encode('\x00\x00\x00\x00\x00\x06\x01\x04\x00\x01\x00\x02')
mySocket.send(message)
data = codecs.decode(mySocket.recv(1024))
print ('Received from server: ' + data)
mySocket.close()
if __name__ == '__main__':
Main()
报错
File "C:\Python34\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 11: invalid start byte
我正在尝试连接到 Ananas - Modbus/TCP -server
错误是什么?
谢谢!
这是因为它试图将data
转换为utf-8字符串(并且其中包含的某些字节无法用utf-8表示)。
如果您想查看字节数组的十六进制值,您可以:
Python3.5+
data = mySocket.recv(1024)
data.hex()
Othewrise
>>> import binascii
>>> data = mySocket.recv(1024)
>>> data = binascii.hexlify(data).decode()
我卡在这个套接字客户端Python3代码:
import socket
import codecs
def Main():
host = '127.0.0.2'
port = 502
mySocket = socket.socket()
mySocket.connect((host,port))
message = codecs.encode('\x00\x00\x00\x00\x00\x06\x01\x04\x00\x01\x00\x02')
mySocket.send(message)
data = codecs.decode(mySocket.recv(1024))
print ('Received from server: ' + data)
mySocket.close()
if __name__ == '__main__':
Main()
报错
File "C:\Python34\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 11: invalid start byte
我正在尝试连接到 Ananas - Modbus/TCP -server
错误是什么?
谢谢!
这是因为它试图将data
转换为utf-8字符串(并且其中包含的某些字节无法用utf-8表示)。
如果您想查看字节数组的十六进制值,您可以:
Python3.5+
data = mySocket.recv(1024)
data.hex()
Othewrise
>>> import binascii
>>> data = mySocket.recv(1024)
>>> data = binascii.hexlify(data).decode()