nodejs websocket检测断开连接的套接字

时间:2016-02-19 11:11:49

标签: node.js html5 websocket

我有一个nodejs websocket服务器,我有以下问题。

当我的客户端连接到服务器并正常终止时,在这些套接字上调用onclose方法,并在关闭的套接字上执行清理操作。

当客户端由于网络而断开连接时,不会调用onclose方法。是否设置了超时,以便在超时后自动调用onclose

我在nodejs中使用ws包作为websocket服务器

4 个答案:

答案 0 :(得分:16)

默认ws实现没有从客户端

断开网络连接的回调

您可以找到keepAlive实施here

答案 1 :(得分:3)

我会尝试用两个例子回答你的问题。尝试分析它们并了解它们的工作原理。它们都经过测试和工作。

  

1- Websocket:

服务器:

var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(3000, function() {
    console.log((new Date()) + ' Server is listening on port 3000');
});

wsServer = new WebSocketServer({
    httpServer: server,
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
  return true;
}

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      request.reject();
      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
      return;
    }

    var connection = request.accept('echo-protocol', request.origin);
    console.log((new Date()) + ' Connection accepted.');
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            connection.sendUTF(message.utf8Data);
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });
    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});

客户端:

<!DOCTYPE html>
<html>
<head>
    <title>Web socket Experiment</title>
    <script type="text/javascript">
        function callWebSocket() {

            var socket = new WebSocket("ws://localhost:3000", 'echo-protocol');

            socket.onopen = function () {
                alert("Hello, Connected To WS server");
            };

            socket.onmessage = function (e) {
                alert("The message received is : " + e.data);
            };
            socket.onerror = function (e) {
                alert("An error occured while connecting... " + e.data);
            };
            socket.onclose = function () {
                alert("hello.. The coonection has been clsoed");
            };

        }
    </script>
</head>

<body>
    <input type="button" value="Open Connecton" onclick="callWebSocket()" />
</body>
</html>
  

2- Socket.io:

服务器:

var http = require('http');
    var app = require('express')();
    var httpServer = http.createServer(app)
    var io = require('socket.io')(httpServer);

app.get('/', function(req, res) {
    res.sendfile(__dirname + '/index.html');
});

io.on('connection', function(socket) {
    socket.emit('news', {
        hello: 'world'
    });
    socket.on('my other event', function(data) {
        console.log(data);
    });
    socket.on('disconnect', function(data) {
        console.log('disconnect!');
    });
});

httpServer.listen(3000);

客户端:

<html>
<head>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
  var conn_options = {
    'sync disconnect on unload':false
  };
  var socket = io.connect('http://localhost:3000',conn_options);
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>
</head>
<body>
</body>
</html>

答案 2 :(得分:2)

要检测断开连接,您需要拥有一些流量。如果您的应用程序产生持续流量,那么您可以在每次收到某些内容时执行重置计数器等操作,并在计数器用完时考虑连接失败。

否则,您应该能够使用WebSocket提供的ping。这些不会在浏览器中公开,但是Node.js的WebSocket库可能允许您打开它们并在ping失败时收到通知。

答案 3 :(得分:0)

您可以在官方库documentation中对其进行检查。我不想在这里复制粘贴,因为它可能很快就会过时。