2

I am stuck in this socket client Python3 code:

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

I am trying to connect to a Ananas - Modbus/TCP -server

What is the error?

Thanks!

1 Answer 1

5

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).

If you want to see the hexadecial value of a byte array you can:

Python3.5+

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

Othewrise

>>> import binascii
>>> data = mySocket.recv(1024)
>>> data = binascii.hexlify(data).decode()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.