Search code examples
pythonsocketstcp

python tcp socket wrong value


I used python connect A rfid device by tcp socket.

here is the base code

HOST = '192.168.1.159'
PORT = 4001
from socket import *
def main():
    tcp_client_socket = socket(AF_INET,SOCK_STREAM)
    tcp_client_socket.connect((HOST,PORT))
    while True:
        recv_data = tcp_client_socket.recv(10240)
        if recv_data:
            print(recv_data)
        else:
            break
    tcp_client_socket.close()
if __name__ == '__main__':
    main()

then I'll receive the value like this

b'\xa0\x13\x01\x89\x1c4\x000\x083\xb2\xdd\xd9\x01@\x00\x00\x00\xa4pK'

but the tcp socket test tool receive the value like this

A0 13 01 89 1C 34 00 30 08 33 B2 DD D9 01 40 00 00 00 A4 70 4B

enter image description here

check the Highlight part.

I tred

print(recv_data.decode())

then receive

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 0: invalid start byte

I don't know how to fix this issue. can someboy help? please.


Solution

  • I solved my question

    print(recv_data.hex())
    

    then receive

    a00a018900000500000001c6
    

    and send data

        packet = bytearray()
        packet.append(0xA0)
        packet.append(0x04)
        packet.append(0x01)
        packet.append(0x74)
        packet.append(0x00)
        packet.append(0xE7)
        packet.append(0xA0)
        packet.append(0x04)
        packet.append(0x01)
        packet.append(0x89)
        packet.append(0x01)
        packet.append(0xD1)
        tcp_client_socket.send(packet)