Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/443.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.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
Javascript NodeJS Websockets-发送数据后终止套接字_Javascript_Node.js_Websocket_Terminate - Fatal编程技术网

Javascript NodeJS Websockets-发送数据后终止套接字

Javascript NodeJS Websockets-发送数据后终止套接字,javascript,node.js,websocket,terminate,Javascript,Node.js,Websocket,Terminate,我正在使用ws包在nodeJS中创建WebSocket 但是,我要做的是,一旦数据发送到服务器,套接字必须终止。我不知道该怎么做 我的代码现在看起来像这样,但这里的问题是在发送任何数据之前终止 ws.on('open', function open() { console.log('subscribing'); ws.send(creds); ws.terminate(); resolve(1); });

我正在使用ws包在nodeJS中创建WebSocket

但是,我要做的是,一旦数据发送到服务器,套接字必须终止。我不知道该怎么做

我的代码现在看起来像这样,但这里的问题是在发送任何数据之前终止

        ws.on('open', function open() {
        console.log('subscribing');
        ws.send(creds);
        ws.terminate();
        resolve(1);
    });

做这件事的正确方法是什么?

编辑:我可能已经将客户端与服务器端进行了切换,但概念仍然是一样的。您需要一个确认信号才能发回

这不是websocket问题。这是一个TCP/IP问题。当您发送数据时,您可能知道数据何时从网络适配器的缓冲区中清除,但无法知道最后一个数据包何时(或是否)到达另一个端点

这是所有TCP/IP连接的常见问题,我在几个用例中发现的唯一绝对安全的解决方案是像这样向客户端发送ACK(确认)

在服务器上,收到消息后:

ws.send(""); // acknowledge the server received the message
// don't close the connection, linger instead
// process the message...
在客户机上:

// create ws and immediately set a flag
ws.lingering = false;

// attach receive event before you open the socket
ws.on("data", function () {
  if (ws.lingering)
  {
    // now you can terminate the connection
    ws.terminate();
    resolve(1);
  }
});

// now open the socket and send message without terminating, yet
ws.on("open", function () {
    console.log("subscribing...");
    ws.send(creds);
    ws.lingering = true;
});

您可能会注意到,服务器发送的消息没有在客户端上进行检查,它只是一个等待的信号。

这就是您如何优雅地终止它的方式:

ws.close()
但请注意,除非客户机回复您,否则您无法从服务器知道数据何时到达客户机。因此,您应该做的是创建另一个事件,确保客户端已收到数据并回复您,然后在该事件上终止其连接

    ws.on('open', function open() {
    console.log('subscribing');
    ws.send(creds);
});

    ws.on('credsanswer', function incoming(message) {
    //user has received creds ands calls us back
    ws.close()
});