使用websockets处理连接丢失

时间:2014-11-17 10:52:52

标签: javascript firefox websocket firefox-addon

我最近设置了一个本地WebSocket服务器工作正常但是我有一些麻烦,了解我应该如何处理客户端或服务器故意启动的突然断开连接,即:服务器断电,以太网电缆拔出等...我需要客户端知道连接是否在~10秒内丢失。

客户端,连接简单:

var websocket_conn = new WebSocket('ws://192.168.0.5:3000');

websocket_conn.onopen = function(e) {
    console.log('Connected!');
};

websocket_conn.onclose = function(e) {
    console.log('Disconnected!');
};

我可以手动触发连接断开,工作正常,

websocket_conn.close();

但是,如果我只是将以太网电缆从计算机背面拔出,或者禁用了连接,则onclose不会被调用。我在另一篇文章中看到它最终会在TCP detects loss of connectivity时被调用,但是我不需要及时作为Firefox的默认设置我相信是10分钟,我真的不想去大约数百台计算机about:config更改此值。我读过的唯一其他建议是使用'ping / pong'保持活动的轮询样式方法,这似乎与websockets的想法相违背。

有没有更简单的方法来检测这种断开行为?从技术角度看,我正在阅读的旧帖子是否仍然是最新的,最好的方法仍然是'ping / pong'风格?

4 个答案:

答案 0 :(得分:24)

您必须添加乒乓方法

接收 __ ping __ 发送 __ pong __ 后,在服务器中创建代码

JavaScript代码在下面给出

function ping() {
        ws.send('__ping__');
        tm = setTimeout(function () {

           /// ---connection closed ///


    }, 5000);
}

function pong() {
    clearTimeout(tm);
}
websocket_conn.onopen = function () {
    setInterval(ping, 30000);
}
websocket_conn.onmessage = function (evt) {
    var msg = evt.data;
    if (msg == '__pong__') {
        pong();
        return;
    }
    //////-- other operation --//
}

答案 1 :(得分:7)

这是我最终做的解决方案,目前似乎工作得很好,它完全针对我的项目设置&依赖于我在问题中最初没有提到的标准,但如果他们碰巧做同样的事情,它可能对其他人有用。

与websocket服务器的连接发生在Firefox插件中,默认情况下,Firefox的TCP设置有10分钟超时。您可以使用about:config查看其他详细信息并搜索TCP。

Firefox插件可以访问这些参数

var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);

并通过指定分支&更改这些参数。偏好以及新值

prefs.getBranch("network.http.tcp_keepalive.").setIntPref('long_lived_idle_time', 10);

现在,安装了插件的任何计算机都有10秒的TCP连接超时。如果连接丢失,则会触发onclose事件,该事件会显示警报并尝试重新建立连接

websocket_conn.onclose = function (e) {
    document.getElementById('websocket_no_connection').style.display = 'block';
    setTimeout(my_extension.setup_websockets, 10000);
}; 

答案 2 :(得分:4)

我使用了ping / pong的想法,效果很好。这是我在server.js文件中的实现:

var SOCKET_CONNECTING = 0;
var SOCKET_OPEN = 1;
var SOCKET_CLOSING = 2;
var SOCKET_CLOSED = 3;

var WebSocketServer = require('ws').Server
wss = new WebSocketServer({ port: 8081 });

//Broadcast method to send message to all the users
wss.broadcast = function broadcast(data,sentBy)
{
  for (var i in this.clients)
  {
    if(this.clients[i] != sentBy)
    {
      this.clients[i].send(data);
    }
  }
};

//Send message to all the users
wss.broadcast = function broadcast(data,sentBy)
{
  for (var i in this.clients)
  {
    this.clients[i].send(data);
  }
};

var userList = [];
var keepAlive = null;
var keepAliveInterval = 5000; //5 seconds

//JSON string parser
function isJson(str)
{
 try {
    JSON.parse(str);
  }
  catch (e) {
    return false;
  }
  return true;
}

//WebSocket connection open handler
wss.on('connection', function connection(ws) {

  function ping(client) {
    if (ws.readyState === SOCKET_OPEN) {
      ws.send('__ping__');
    } else {
      console.log('Server - connection has been closed for client ' + client);
      removeUser(client);
    }
  }

  function removeUser(client) {

    console.log('Server - removing user: ' + client)

    var found = false;
    for (var i = 0; i < userList.length; i++) {
      if (userList[i].name === client) {
        userList.splice(i, 1);
        found = true;
      }
    }

    //send out the updated users list
    if (found) {
      wss.broadcast(JSON.stringify({userList: userList}));
    };

    return found;
  }

  function pong(client) {
    console.log('Server - ' + client + ' is still active');
    clearTimeout(keepAlive);
    setTimeout(function () {
      ping(client);
    }, keepAliveInterval);
  }

  //WebSocket message receive handler
  ws.on('message', function incoming(message) {
    if (isJson(message)) {
      var obj = JSON.parse(message);

      //client is responding to keepAlive
      if (obj.keepAlive !== undefined) {
        pong(obj.keepAlive.toLowerCase());
      }

      if (obj.action === 'join') {
        console.log('Server - joining', obj);

        //start pinging to keep alive
        ping(obj.name.toLocaleLowerCase());

        if (userList.filter(function(e) { return e.name == obj.name.toLowerCase(); }).length <= 0) {
          userList.push({name: obj.name.toLowerCase()});
        }

        wss.broadcast(JSON.stringify({userList: userList}));
        console.log('Server - broadcasting user list', userList);
      }
    }

    console.log('Server - received: %s', message.toString());
    return false;
  });
});

这是我的index.html文件:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
        <title>Socket Test</title>
    </head>
    <body>
        <div id="loading" style="display: none">
            <p align="center">
                LOADING...
            </p>
        </div>
        <div id="login">
            <p align="center">
                <label for="name">Enter Your Name:</label>
                <input type="text" id="name" />
                <select id="role">
                    <option value="0">Attendee</option>
                    <option value="1">Presenter</option>
                </select>
                <button type="submit" onClick="login(document.getElementById('name').value, document.getElementById('role').value)">
                    Join
                </button>
            </p>
        </div>
        <div id="presentation" style="display: none">
            <div class="slides">
                <section>Slide 1</section>
                <section>Slide 2</section>
            </div>
            <div id="online" style="font-size: 12px; width: 200px">
                <strong>Users Online</strong>
                <div id="userList">
                </div>
            </div>
        </div>
        <script>
            function isJson(str) {
                try {
                   JSON.parse(str);
                }
                catch (e) {
                   return false;
                }
                return true;
            }

            var ws;
            var isChangedByMe = true;
            var name = document.getElementById('name').value;
            var role = document.getElementById('role').value;

            function init()
            {
                loading = true;
                ws = new WebSocket('wss://web-sockets-design1online.c9users.io:8081');

                //Connection open event handler
                ws.onopen = function(evt)
                {
                    ws.send(JSON.stringify({action: 'connect', name: name, role: role}));
                }

                ws.onerror = function (msg) {
                    alert('socket error:' + msg.toString());
                }

                //if their socket closes unexpectedly, re-establish the connection
                ws.onclose = function() {
                    init();
                }

                //Event Handler to receive messages from server
                ws.onmessage = function(message)
                {
                    console.log('Client - received socket message: '+ message.data.toString());
                    document.getElementById('loading').style.display = 'none';

                    if (message.data) {

                        obj = message.data;

                        if (obj.userList) {

                            //remove the current users in the list
                            userListElement = document.getElementById('userList');

                            while (userListElement.hasChildNodes()) {
                                userListElement.removeChild(userListElement.lastChild);
                            }

                            //add on the new users to the list
                            for (var i = 0; i < obj.userList.length; i++) {

                                var span = document.createElement('span');
                                span.className = 'user';
                                span.style.display = 'block';
                                span.innerHTML = obj.userList[i].name;
                                userListElement.appendChild(span);
                            }
                        }
                    }

                    if (message.data === '__ping__') {
                        ws.send(JSON.stringify({keepAlive: name}));
                    }

                    return false;
                }
            }

            function login(userName, userRole) {

                if (!userName) {
                    alert('You must enter a name.');
                    return false;
                } 

                //set the global variables
                name = userName;
                role = userRole;

                document.getElementById('loading').style.display = 'block';
                document.getElementById('presentation').style.display = 'none';
                document.getElementById('login').style.display = 'none';
                init();
            }
        </script>
    </body>
</html>

如果你想自己尝试一下,这里是指向云9沙箱的链接:https://ide.c9.io/design1online/web-sockets

答案 3 :(得分:1)

websocket协议定义control frames for ping and pong。所以基本上,如果服务器发送ping,浏览器将用pong回答,它应该也可以反过来工作。您使用的WebSocket服务器可能会实现它们,您可以定义浏览器必须响应或被视为死机的超时。对于您在浏览器和服务器中的实现,这应该是透明的。

您可以使用它们来检测半开放连接:http://blog.stephencleary.com/2009/05/detection-of-half-open-dropped.html

也相关:WebSockets ping/pong, why not TCP keepalive?