Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何使用HTTPs保持活动请求中的多个JSON?_Node.js_Json_Http_Stream_Keep Alive - Fatal编程技术网

Node.js 如何使用HTTPs保持活动请求中的多个JSON?

Node.js 如何使用HTTPs保持活动请求中的多个JSON?,node.js,json,http,stream,keep-alive,Node.js,Json,Http,Stream,Keep Alive,我有一个节点web服务器,可以监听 this.app.use('/register-receiver', (req, res) => { const receiverId = req.query.id; res.status(200).set({ connection: 'keep-alive', 'Cache-Control': 'no-cache', 'Content-Type': 'application/json', }); this.rec

我有一个节点web服务器,可以监听

this.app.use('/register-receiver', (req, res) => {
  const receiverId = req.query.id;
  res.status(200).set({
    connection: 'keep-alive',
    'Cache-Control': 'no-cache',
    'Content-Type': 'application/json',
  });
  this.receivers[receiverId] = res;
});
它定期将JSON有效负载发送到连接到
/register receiver
的客户端

this.receivers[receiverId].write(JSON.stringify({
  // some big json
}))
我有另一个节点程序,它充当启动时连接到服务器的客户端

const options = {
  agent: false,
  host: <my host>,
  defaultPort: <my port>
  path: `/register-receiver?id=${activeConfig.receiver.id}`
  headers: {
    connection: 'keep-alive',
    'Content-Type': 'application/json',
  }
};

http.get(options, res => {
  res.setEncoding('utf8');
  res.on('data', data => {
    try {
      const response = JSON.parse(data);
      // do stuff with response
    } catch(e) {
      console.log(`error ${e} with ${data}`);
    }
  });
  res.on('end', () => console.log(`connection finished`) )
})
const选项={
代理人:错,
主持人:,
默认端口:
路径:`/register receiver?id=${activeConfig.receiver.id}`
标题:{
连接:“保持活力”,
“内容类型”:“应用程序/json”,
}
};
http.get(选项,res=>{
res.setEncoding('utf8');
res.on('data',data=>{
试一试{
const response=JSON.parse(数据);
//用回应做事情
}捕获(e){
log(`error${e}with${data}`);
}
});
res.on('end',()=>console.log('connection finished'))
})
服务器需要定期向客户端发送JSON有效负载。客户机应该接收这些JSON并对其进行处理。然而,问题是大型JSON写入被分块,这样客户机将接收到分段的JSON。这破坏了JSON.parse(data),现在客户端不知道如何处理服务器有效负载。我不能依靠
res.on('end')
来检测分块写入的完成情况,因为这是一个保持活动的请求,应该永远保持打开状态

我不想设计自己的协议来组合JSON块,因为它很复杂。这并不像串接字符串那么简单,因为如果服务器同时发送2个大的JSON有效负载,我可能会有交错的JSON块


是否可以强制服务器将整个JSON作为一个块写入流中?如何设置客户端,使其与服务器建立“永久”连接并侦听完整的JSON有效负载?

欢迎使用TCP/IP。您无法控制它到达的数据包。您需要一个长度或一个描绘器来知道在解析之前读取多少或一个流PARS.FIY,您可能需要考虑WebSoCor或SoCKET.IO,它将为您重新组装完整的消息。但我认为最好通过WebSoCub和Publisher/Public模型通过PubSub队列考虑WebSoCube,但我决定不支持它,因为我只需要1路通信。如果使用长度,我将如何指定每个JSON负载的长度?若我使用一个描述器,我能保证“块大小”使每个块包含一个可预测的json片段吗?