Last active
July 31, 2021 19:46
-
-
Save jgcasta/0993baa06bda6be5a1ab to your computer and use it in GitHub Desktop.
Python socket server to receive binary data and parse the content as integer and string values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Imports are missing