Skip to content

Instantly share code, notes, and snippets.

@OzTamir
Last active August 29, 2015 13:56
Show Gist options
  • Save OzTamir/8873114 to your computer and use it in GitHub Desktop.
Save OzTamir/8873114 to your computer and use it in GitHub Desktop.
Parse socket-recived dictionaries in the following format = {Key:Value,Key:Value} (sorry for lack of standards)
#!/usr/bin/env python
import socket
DATA = {}
def parser(*args):
'''Parse key-value pairs recived from client'''
new_data = {}
dict_data = args[0]
for pair in dict_data:
key, value = pair.split(':')
if value.isdigit():
value = int(value)
new_data[key] = value
return new_data
def server(port=4590):
global DATA
# Create a socket and establish connection
server = socket.socket()
server.bind(('0.0.0.0', port))
server.listen(2)
# Get client's socket object
try:
client, address = server.accept()
print 'Client connected from {IP}:{PORT}'.format(IP = address[0], PORT = address[1])
recived = str(client.recv(1024))
# Reciving loop
while True:
recived += str(client.recv(1024))
if recived.find('}') != -1:
recived = recived[recived.find('{') + 1:recived.find('}')]
recived = recived.split(',')
DATA.update(parser(recived))
recived = ''
print 'Parsed Dictionary:'
print DATA
print '------------'
client.close()
client, address = server.accept()
# Handle exceptions
except Exception, e:
print str(e)
except KeyboardInterrupt:
print '\nUser Terminated server.'
finally:
# Close the socket and terminate the connection
print 'Closing server...'
server.close()
if __name__ == '__main__':
server()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment