'Send Hexadecimal string to socket using python
Dear friends this is a humble request to solve my problem with example please. I am working on RFID sensors in which i need to send Hexadecimal data to socket. here is my code
import socket
HOST = '192.168.0.115'
PORT = 20108
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
DATA = 'A5 5A 00 08 04 0C 0D 0A'
s.send(DATA)
data = s.recv(4096)
s.close()
d = data.encode('hex').upper()
print 'Received', repr(d)
this code is sending DATA in string format but i need to send the DATA in Hexadecimal format because the RFID reader can read Hexadecimal data... i already use struct.pack but it is not working for me or may be I don't know how to use it...
the DATA is same "A5 5A 00 08 04 0C 0D 0A" this but how do i send this in Hexadecimal format... for example if sock.send("") sending string. in need to send socket.send(hexadecimal)???
Solution 1:[1]
Think this has already been answered Pyhton Send receive hex data via tcp socket
You may want to convert your text first into hex format for RFID to understand:
'01AF23'.decode('hex')
Solution 2:[2]
Python has a built in hexadecimal type. You will need to serialize that as a string before sending it; as socket.send only accepts strings.
Edit: After re-reading your question, it seems you aren't encoding the received value as a hex type. With that said, if you choose to serialize your data before sending it, you just unserialize it on the receiving end.
References:
See Python serialization: https://docs.python.org/2/library/pickle.html
See Python Hex type: https://docs.python.org/2/library/functions.html#hex
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
| Solution 2 |
