I've never done python programming before, so I'm hoping you guys can give me some feedback in my code.
I have a node js tcp server that must receive a json "request" object and then will respond with several other json objects, asynchronously.
I need python to read all that json, one by one, and return to a callback, until the server sends a object that represents the "end" of the response.
Am I doing it correctly?
def requestServer(onData, options={}):
opts = {'command': 'request'}
socket = connect()
opts.update(options)
socket.send(json.dumps(opts)) # send the json request to the server
while(True):
data = socket.recv(1024*5) #reads back any response
if(data):
data = json.loads(data)
if('responseType' in data and data['responseType'] == 'end'):
break # end of response
else:
onData(data)
time.sleep(0.1)
socket.close()
def connect():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8888))
return s
Then I can use it like this:
def onData(data):
print("Data received from server: ")
print(data)
requestServer(onData, {'some': 'options'})