Python socket server to receive binary data and parse the content as integer and string values
#!/usr/bin/python
#-*- coding: utf-8 -*-
'''
Jose Gomez Castano
jgcasta@gmail.com
Socket server to receive binary data and parse the content as integer and string values
Sample packet 030b94 received is decoded as decimal string values
hex Decimal
03 03
0b94 2964
'''
import socket
import struct
import binascii
HOST = ''
PORT = 3000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.error as msg:
s.close()
print 'Bind fallido. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
s.listen(1)
print 'Listening Socket'
while True:
sc, addr = s.accept()
while True:
recibido = sc.recv(1024)
if not recibido: break
b = bytearray(recibido)
test = binascii.hexlify(b)
print '-----------------------------------------------------'
print 'Message received at : ' + datetime.datetime.now().strftime("%H:%M:%S.%f")
print 'Message ' + test
print 'First attribute ' + test[0:2] + ' -> ' + str(int('0x' + test[0:2],0))
print 'Second attribute ' + test[2:6] + ' -> ' + str(int('0x' + test[2:6],0))
sc.close()
s.close()