Skip to content

Instantly share code, notes, and snippets.

@jgcasta
Last active July 31, 2021 19:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jgcasta/0993baa06bda6be5a1ab to your computer and use it in GitHub Desktop.
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
#!/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()
@tmkasun
Copy link

tmkasun commented Nov 23, 2018

import sys
import datetime

Imports are missing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment