JavaScript WebSocket replace reference with new socket

时间:2019-04-17 01:10:32

标签: javascript websocket

I'm trying to reconnect a websocket automatically with a function. I want it to keep the same variable name, but i'm having some issues. here is the function I'm using

function reconnect(obj){
    try{
        obj=new WebSocket(obj.url);
        }
     except{
        setTimeout(reconnect,5000,obj);
    }
}

mysocket=new Websocket(myurl);
mysocket.close()
reconnect(mysocket)

After the reconnect function runs successfully but mysocket is still referenced to the old closed Websocket. I'm not sure how to transfer to new Websocket object to the old variable.

2 个答案:

答案 0 :(得分:2)

You are overriding the variable. There are multiple ways to do it, quickest would be to pass an object.

function reconnect(obj){
    var mySocket = obj.mySocket;
    try {
        obj.mySocket=new WebSocket(mySocket.url);
    }
    except {
        setTimeout(reconnect, 5000, obj);
    }
}

mysocket=new Websocket(myurl);
mysocket.close()
var wrapperObject = {mysocket};
reconnect(wrapperObject);
// At any point of time `wrapperObject.mysocket` will have the latest socket instance

A more cleaner approach would be to define a wrapper class/function which scopes the mySocket variable privately. EX:

function ReconnectSocket (mySocket) {
    this.mySocket = mySocket
}

ReconnectSocket.prototype.reconnect = function () {
    try {
        this.mySocket = new WebSocket(this.mySocket.url);
    }
    except {
        setTimeout(reconnect, 5000);
    }
}

ReconnectSocket.prototype.getSocket = function () {
    return this.mySocket
}

var mysocket=new Websocket(myurl);
mysocket.close()
var reconnectSocket = new ReconnectSocket(mysocket).reconnect()
// `reconnectSocket.getSocket()` will give the latest instance at any point of time

答案 1 :(得分:0)

First approach is using global variable

    function reconnect(){
        try{
            mysocket=new WebSocket(mysocket.url);
            }
         except{
            setTimeout(reconnect,5000);
        }
    }

    mysocket=new Websocket(myurl);
    mysocket.close()
    reconnect()

Second approach, I think you should wrap your socket in a object

    function reconnect(obj){
        try{
            obj.mysocket=new WebSocket(obj.mysocket.url);
            }
         except{
            setTimeout(reconnect,5000,obj);
        }
    }

    var socketObject = {};
    socketObject.mysocket=new Websocket(myurl);
    socketObject.mysocket.close()
    reconnect(socketObject)