Connection management in command based socket API in node.js

I built a RESTful API based on expresss.js that communicates with a remote server through a TCP socket using JSON. The requested URLs are converted to the corresponding JSON messages, a new TCP socket is open, and a message is sent. Then, when a message is received from the same connection, an event is executed, the JSON response is evaluated, and a new JSON message is returned as a result of the GET request.

Possible ways:

  • Async (currently in use) - open a server connection for each request.
  • Sync - creating a queue with all requests and waiting for a response, blocking code.
  • Track - send the entire request immediately and receive answers asynchronously. Use the tracker identifier in the request to associate each request with its response.

What will be the best direction? Is there a common template for solving this kind of application?

+4
source share
1 answer

1 (async, a new connection for each request) is probably the easiest to implement.

If you want to reuse a socket for efficient use, you have to come up with your own keep-alive mechanism - essentially streaming multiple requests and responses using the same socket.

I would use double CRLF ('\ n \ r \ n \ r') as a separator for each JSON request, fire a request event for each request and just write the response asynchronously. It is possible to stream without delimiters, but this requires additional parsing when you get a partial JSON string from a socket.

+1
source

Source: https://habr.com/ru/post/1447976/


All Articles