Created
March 9, 2015 09:58
-
-
Save rif/771c5867badd4912c30b to your computer and use it in GitHub Desktop.
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
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