服务器在WebSocket中重新启动时重新连接客户端

时间:2010-09-23 16:30:15

标签: websocket

我使用PHP5和Chrome浏览器作为客户端使用Web套接字。 我从网站http://code.google.com/p/phpwebsocket/获取了代码。

我运行服务器,客户端也已连接。我也可以聊天。 现在,当我重新启动服务器(通过杀死它并再次启动它)时, 客户端获取断开连接的信息,但在发送消息时自动不与服务器重新连接。

如何实现这一目标?就像我收到断开连接的信息一样,我应该检查它并将其发送到JavaScript以刷新页面或重新连接吗?

9 个答案:

答案 0 :(得分:129)

当服务器重新启动时,Web Socket连接将关闭,因此会触发JavaScript onclose事件。这是一个尝试每五秒重新连接的示例。

function start(websocketServerLocation){
    ws = new WebSocket(websocketServerLocation);
    ws.onmessage = function(evt) { alert('message received'); };
    ws.onclose = function(){
        // Try to reconnect in 5 seconds
        setTimeout(function(){start(websocketServerLocation)}, 5000);
    };
}

答案 1 :(得分:37)

Andrew提供的解决方案并不完美,因为如果连接丢失,服务器可能会发送几个关闭事件。

在这种情况下,你将设置几个setTimout。安德鲁给出的解决方案可能仅在服务器在五秒钟之前就绪时才会起作用。

然后,基于Andrew解决方案,重新设计,我已经使用setInterval将ID附加到窗口对象(这样它可以“无处不在”):

var timerID=0;

var socket;

/* Initiate what has to be done */

socket.onopen=function(event){
 /* As what was before */
 if(window.timerID){ /* a setInterval has been fired */
   window.clearInterval(window.timerID);
   window.timerID=0;
 }
 /* ... */
}

socket.onclose=function(event){
  /* ... */
 if(!window.timerID){ /* Avoid firing a new setInterval, after one has been done */
  window.timerID=setInterval(function(){start(websocketServerLocation)}, 5000);
 }
 /* That way, setInterval will be fired only once after losing connection */
 /* ... */
}

答案 2 :(得分:31)

ReconnectingWebSocket

GitHub托管一个小型JavaScript库,它装饰WebSocket API以提供WebSocket连接,如果连接断开,它将自动重新连接。

使用gzip压缩的缩小库少于600个字节。

官方存储库可在此处获取:

https://github.com/joewalnes/reconnecting-websocket

服务器泛洪

如果重新启动时有大量客户端连接到服务器。 使用指数退避算法管理客户端的重新连接时序可能是值得的。

算法的工作原理如下:

  1. 对于k次尝试,生成0到2 ^ k - 1之间的随机时间间隔,
  2. 如果您可以重新连接,请将k重置为1,
  3. 如果重新连接失败,则k增加1,并且该过程在步骤1重新开始,
  4. 要截断最大间隔,当达到一定数量的尝试次数k时,k会在每次尝试后停止增加。
  5. 参考:

    http://blog.johnryding.com/post/78544969349/how-to-reconnect-web-sockets-in-a-realtime-web-app

      

    使用此算法重新连接WebSocket不会处理重新连接。

答案 3 :(得分:26)

我一直在使用这个patten一段时间用于纯粹的vanilla JavaScript,并且它比其他答案支持更多的情况。

document.addEventListener("DOMContentLoaded", function() {

  'use strict';

  var ws = null;

  function start(){

    ws = new WebSocket("ws://localhost/");
    ws.onopen = function(){
      console.log('connected!');
    };
    ws.onmessage = function(e){
      console.log(e.data);
    };
    ws.onclose = function(){
      console.log('closed!');
      //reconnect now
      check();
    };

  }

  function check(){
    if(!ws || ws.readyState == 3) start();
  }

  start();

  setInterval(check, 5000);


});

一旦服务器关闭连接,这将重试,它将检查连接以确保它每隔5秒就会启动。

因此,如果服务器在运行时或在onclose事件发生时未启动,则一旦重新联机,连接仍会返回。

注意:使用此脚本将不允许您停止尝试打开连接...但我认为这是您想要的?

答案 4 :(得分:2)

以下是我在项目中使用的代码,它100%工作。

  1. 将所有websocket代码放在init函数中。
  2. 在onclose回调中再次调用init。
  3. 最后在文档就绪函数中调用init函数。
  4. var name = sessionStorage.getItem('name');

    wsUri =  "ws://localhost:8080";   
    var websocket;
    $(function() {  
        init();  
        $("#chat_text_box").on("keypress", function(e) {         
            if (e.keyCode == 13) {   //For Enter Button    
                e.preventDefault();
                var mymessage = $('#chat_text_box').val();               
                if(mymessage){
                    var msg = {  type: 'chat_text',  data : {  name:name,  msg:mymessage }  };                
                    console.log(msg);
                    websocket.send(JSON.stringify(msg));
                    $('#chat_text_box').val('');
                }               
                return false;                       
            }        
        });      
    });     
    function init() { 
        websocket = new WebSocket(wsUri);      
        websocket.onopen = function(ev) { /*connection is open */    } 
        websocket.onmessage = function(ev) {        
            var data = JSON.parse(ev.data); //PHP sends Json data        
            var type = data.type;//alert(JSON.stringify(data));
            switch(type) {
                case "chat_text":
                    var text = "<div><span class='user'>"+data.data.sender_name+" : </span><span class='msg'>"+data.data.msg+"</span></div>";
                    $('#chat-messages').append(text);
                    break;            
                default:
                    break;
    
            }        
    
        };     
        websocket.onerror   = function(ev){}; 
        websocket.onclose = function(ev) {   init();   };  
    }
    

答案 5 :(得分:2)

无法评论,但以下内容:

var socket;

const socketMessageListener = (event) => {
  console.log(event.data);
};

const socketOpenListener = (event) => {
  console.log('Connected');
  socket.send('hello');
};

const socketCloseListener = (event) => {
  if (socket) {
    console.error('Disconnected.');
  }
  socket = new WebSocket('ws://localhost:8080');
  socket.addEventListener('open', socketOpenListener);
  socket.addEventListener('message', socketMessageListener);
  socket.addEventListener('close', socketCloseListener);
};

socketCloseListener();

// for testing
setTimeout(()=>{
  socket.close();
},5000);

Plus https://www.npmjs.com/package/back已经足够好了:))

答案 6 :(得分:1)

function wsConnection(url){
    var ws = new WebSocket(url);
    var s = (l)=>console.log(l);
	ws.onopen = m=>s(" CONNECTED")
    ws.onmessage = m=>s(" RECEIVED: "+JSON.parse(m.data))
    ws.onerror = e=>s(" ERROR")
    ws.onclose = e=>{
        s(" CONNECTION CLOSED");
        setTimeout((function() {
            var ws2 = new WebSocket(ws.url);
			ws2.onopen=ws.onopen;
            ws2.onmessage = ws.onmessage;
            ws2.onclose = ws.onclose;
            ws2.onerror = ws.onerror;
            ws = ws2
        }
        ).bind(this), 5000)
    }
    var f = m=>ws.send(JSON.stringify(m)) || "Sent: "+m;
    f.ping = ()=>ws.send(JSON.stringify("ping"));
    f.close = ()=>ws.close();
    return f
}

c=new wsConnection('wss://echo.websocket.org');
setTimeout(()=>c("Hello world...orld...orld..orld...d"),5000);
setTimeout(()=>c.close(),10000);
setTimeout(()=>c("I am still alive!"),20000);
<pre>
This code will create a websocket which will 
reconnect automatically after 5 seconds from disconnection.

An automatic disconnection is simulated after 10 seconds.

答案 7 :(得分:0)

最后,我在vue + ts中使ws自动重新连接,如下所示:

private async mounted() {
    // Connect to WebSocket
    const sn = "sb1234567890";
    const host =
        window.location.protocol == "https:"
            ? "wss://www.xxx.net"
            : process.env.DEV_TYPE === "fullstack"
            ? "ws://10.0.0.14:8528"
            : "ws://www.xxx.net:8528";
    const wsUri = host + "/feed-home/" + sn;
    await this.startWs(wsUri, sn);
    // !!!Deprecated: failed to reconnect
    // let ws = new WebSocket();
    // console.log(ws);
    // ws.onopen = async function(event) {
    //     console.log(event, "openEvent");
    //     clearInterval(that.timer);
    // };
    // ws.onclose = async function(event) {
    //     console.log(event, "close");
    //     that.timer = setInterval(() => {
    //         console.log("Heart Beat");
    //         ws.send("HeartBeat");
    //         // ws = new WebSocket("ws://10.0.0.14:8528/feed-home/" + sn);
    //         console.log(ws);
    //     }, 60000);
    // };
    // ws.onmessage = async function(event) {
    //     console.log(event, "ws");
    //     alert("get it!");
    //     await alert("please update!");
    //     await that.getHome(sn);
    // };
}
private wsReconnected: boolean = false; // check whether WebSocket is reconnected
private async startWs(uri: string, sn: string) {
    let that = this;
    let ws = new WebSocket(uri);
    ws.onopen = async () => {
        if (that.wsReconnected) {
            await that.getHome(sn); // Refresh api data after reconnected
        }
        ws.send("Current client version: " + window.version);
    };
    ws.onmessage = async evt => {
        await that.getHome(sn);
        that.$message({
            type: "success",
            message: evt.data,
            showClose: true,
            center: true,
            duration: 20 * 1000
        });
    };
    ws.onclose = async () => {
        that.wsReconnected = true;
        await that.startWs(uri, sn);
        const sleep = (seconds: number) => {
            return new Promise(resolve =>
                setTimeout(resolve, seconds * 1000)
            );
        };
        await sleep(10); // Try to reconnect in 10 seconds
        // !!!Deprecated: Use timer will cause multiply ws connections
        // if (!that.wsTimer) {
        //     // Try to reconnect in 10 seconds
        //     that.wsTimer = setInterval(async () => {
        //         console.log("reconnecting websocket...");
        //         await that.startWs(uri, sn);
        //     }, 10 * 1000);
        // }
    };
}

答案 8 :(得分:0)

WebSocket的客户端关闭事件具有 wasClean 属性,这对我很有用。似乎在客户端计算机进入睡眠模式等情况下或在服务器意外停止等情况下将其设置为true。如果手动关闭套接字,则将其设置为false,在这种情况下,您不想打开插座自动再次。下面的代码来自Angular 7项目。我在服务中有此代码,因此可以从任何组件中使用。

    notifySocketClose(event) { 

        if (!event.wasClean) { 
            setTimeout(() => {
                this.setupSocket()
            }, 1000);       
        }
    }

    setupSocket() { // my function to handle opening of socket, event binding etc.
    .....
    .....

            this.websocketConnection = this.websocketConnection ? this.websocketConnection : new WebSocket(socketUrl);
            this.websocketConnection.onclose = this.notifySocketClose.bind(this);   
        } 
    }
    .....
    .....