Skip to content

Instantly share code, notes, and snippets.

@rif
Created March 9, 2015 09:58
Show Gist options
  • Save rif/771c5867badd4912c30b to your computer and use it in GitHub Desktop.
Save rif/771c5867badd4912c30b to your computer and use it in GitHub Desktop.
import json, socket, itertools
class JSONClient(object):
socket = None
def __init__(self, addr):
self.socket = socket.create_connection(addr)
self.id_counter = itertools.count()
def __del__(self):
if self.socket is not None:
self.socket.close()
def call(self, name, *params):
request = dict(id=next(self.id_counter),
params=list(params),
method=name)
self.socket.sendall(json.dumps(request).encode())
# This must loop if resp is bigger than 4K
buffer = ''
data = True
while data:
data = self.socket.recv(4096)
buffer += data
if len(data) < 4096: break
response = json.loads(buffer.decode())
if response.get('id') != request.get('id'):
raise Exception("expected id=%s, received id=%s: %s"
%(request.get('id'), response.get('id'),
response.get('error')))
if response.get('error') is not None:
raise Exception(response.get('error'))
return response.get('result')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment