简体   繁体   English

Python3套接字客户端发送和接收十六进制字符串

[英]Python3 socket client to send and receive hex string

I am stuck in this socket client Python3 code: 我陷入了这个套接字客户端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()

It gives the error 它给出了错误

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 文件“ C:\\ Python34 \\ lib \\ encodings \\ utf_8.py”,第16行,解码返回codecs.utf_8_decode(input,errors,True)UnicodeDecodeError:'utf-8'编解码器无法解码位置11的字节0xb3:无效的起始字节

I am trying to connect to a Ananas - Modbus/TCP -server 我正在尝试连接到Ananas -Modbus / TCP -server

What is the error? 有什么错误?

Thanks! 谢谢!

It's because it try to convert data into an utf-8 string (and some of the bytes contained are not possible to represent in utf-8). 这是因为它尝试将data转换为utf-8字符串(并且其中某些字节无法用utf-8表示)。

If you want to see the hexadecial value of a byte array you can: 如果要查看字节数组的十六进制值,可以:

Python3.5+ Python3.5 +

data = mySocket.recv(1024)
data.hex()

Othewrise Othewrise

>>> import binascii
>>> data = mySocket.recv(1024)
>>> data = binascii.hexlify(data).decode()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM