0

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'})
lucaswxp
  • 2,031
  • 5
  • 23
  • 34
  • 1
    I haven't tried this, but yes this should globally work with the following assumptions and caveats: (a) Your node.js doesn't expect the HTTP protocol, your Python client isn't sending it. That's fine, you say it's a plain TCP server. (b) However, then how do you delimit payloads? You probably have a line-oriented protocol: the client sends one line, the server sends back one line, ad infinitum. (c) If that's the case, then I am not seeing line delimiting reads in your client, so I am not sure how you determine that the JSON payload has fully arrived (it could arrive in 2 chunks for example). – Karel Kubat Mar 05 '15 at 11:24
  • Yes, one line at a time. About the payload, I'm not sure about the chunks... if I'm not mistaken you have to manually program the "chunking logic" by yourself in nodejs, responses are not that big so I'm not worried about that... I have a question: is the time.sleep() there necessary? Or will socket.recv() wait until new data arrives? I don't see anything in the docs. – lucaswxp Mar 05 '15 at 12:12
  • Actually I meant *network* chunks, not chunked transfer encoding. When a server sends bytes, this may arrive at the client in one go or not, that depends on network topology and so on. If your JSON oneliners are short enough, you'll manage to read them in one go. If not, you should `socket.recv()` and append the result to your buffer `data` until nothing more comes in. In any case, `recv()` is blocking, so the `sleep()` is not necessary. (Unless you put the socket in non-blocking mode, but that's a different story that also doesn't involve `sleep()`.) – Karel Kubat Mar 06 '15 at 17:59
  • Using [this RealPython's tutorial](https://realpython.com/python-sockets/#viewing-socket-state) I almost figured it out... I know howto send json data through TCP from the server side to the client with blocking sockets, but couldn't figure it out with non-blocking sockets yet... although with non-blocking the "ping-pong example" worked for me, I am trying to go one step beyond... at least the client part sends multiple messages to the server and the server bounces them back (the basic example in the link for non-blocking). What I'm trying to send back from the server **any variable I want** – SebasSBM Jun 15 '23 at 17:34

0 Answers0