简体   繁体   English

在node.js中管理基于命令的TCP套接字API的连接

[英]Managing connections on a command based TCP socket API in node.js

I built a RESTful API based on expresss.js which communicates to a remote server through a TCP socket using JSON. 我构建了一个基于expresss.js的RESTful API,它使用JSON通过TCP套接字与远程服务器通信。 Requested URLs are converted into the appropriate JSON messages, a new TCP socket is open and the message is sent. 请求的URL将转换为相应的JSON消息,打开一个新的TCP套接字并发送消息。 Then when a message coming from the same connection is received an event is fired, the JSON reply is evaluated and a new JSON message is returned as the result of the GET request. 然后,当收到来自相同连接的消息时,将触发事件,将评估JSON应答,并返回作为GET请求结果的新JSON消息。

Possible paths: 可能的路径:

  1. Async (currently in use) - Open a connection to the server for each request. 异步(当前正在使用) - 为每个请求打开与服务器的连接。
  2. Sync - Create a queue with all the requests and wait for the response, blocking code. 同步 - 创建包含所有请求的队列并等待响应,阻止代码。
  3. Track - Send all the request at once and asynchronously receive the answers. 跟踪 - 立即发送所有请求并异步接收答案。 Use a tracker id on the request to relate each request with its answer. 在请求中使用跟踪器ID将每个请求与其答案相关联。

What will be the best direction to go? 什么是最好的方向? Is there any common pattern to solve this kind of application? 有没有什么共同的模式可以解决这种应用?

1 (async, a new connection for each request) is probably the easiest to implement. 1(异步,每个请求的新连接)可能是最容易实现的。

If you want to reuse the socket for efficiently, you should come up with your own "keep-alive" mechanism - essentially streaming multiple requests and answers using the same socket. 如果您想有效地重用套接字,您应该提出自己的“保持活动”机制 - 基本上使用相同的套接字流式传输多个请求和答案。

I'd probably use double CRLF ('\\n\\r\\n\\r') as the delimiter of each JSON request, fire a 'request' event for each request, and simply write back the answer asynchronously. 我可能会使用双CRLF('\\ n \\ r \\ n \\ n \\ r')作为每个JSON请求的分隔符,为每个请求触发“请求”事件,并简单地异步写回答案。 Delimiter-less streaming is possible, but it requires extra parsing when you receive a partial JSON string from the socket. 可以使用无分隔符的流式传输,但是当您从套接字接收到部分JSON字符串时,它需要额外的解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM