Reconnection of Client when server reboots in WebSocket

后端 未结 9 2212
青春惊慌失措
青春惊慌失措 2020-12-02 05:03

I am using web socket using PHP5 and the Chrome browser as client. I have taken the code from the site http://code.google.com/p/phpwebsocket/.

I run the server, and

9条回答
  •  伪装坚强ぢ
    2020-12-02 05:53

    Below are the codes i have used in my project which working 100%.

    1. Put all the websocket code inside the init function.
    2. Inside the onclose callback call the init again.
    3. Finally call the init function inside the document ready function.

    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 = "
    "+data.data.sender_name+" : "+data.data.msg+"
    "; $('#chat-messages').append(text); break; default: break; } }; websocket.onerror = function(ev){}; websocket.onclose = function(ev) { init(); }; }

提交回复
热议问题