在不创建新实例的情况下重新连接WebSocket [英] Reconnecting a WebSocket without creating a new instance

查看:254
本文介绍了在不创建新实例的情况下重新连接WebSocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我创建了一个新的Web应用程序,该应用程序使用WebSocket连接到Node.JS WebSocket服务器。现在,节点服务器可以完成所需的所有工作,并且可以完美运行。我的问题是浏览器的实现。

So I have created a new web application that uses a WebSocket to Node.JS WebSocket server. Now the Node server does everything it needs to and works perfectly. My problem is with the browser implementation.

我看了很多其他人在回答中提供的库,但是我想看看它们是否是一个更好或更干净的方法。

I have looked at a lot of the libraries other people have been given in the answers, but I want to see if their is a better or cleaner way to do this.

因此,在我的实例中,我实质上创建了一个对象,该对象包装了WebSocket,然后通过调用connect()使用setInterval重新连接 url ),这将创建另一个WebSocket实例。

So in my instance, I essentially create an object, which wraps the WebSocket and then uses a setInterval to reconnect, by calling connect(url), which will create another WebSocket instance.

我一直在查看连接和客户端,如果连接关闭,说服务器出现故障,或者发生了什么事,看起来好像有时候,在更长的时间里,WebSocket连接增加了一倍,所以不是每个客户端1个连接,而是2、3或4 ...?

I have been looking at connections and clients, and it seems that if a connection closes, say the server goes down, or something happens, it looks as though sometimes, in a longer period of time, the WebSocket connections are doubling up, so instead of 1 connection per client, it is 2, 3 or 4...?

我感觉这是因为每次都在创建WebSocket的新实例吗?

I have a feeling this is because I am making a new instance of the WebSocket each time?

下面的代码:

// Main Function
function WSWrapper() {

    // Variables
    this.socket = null;
    this.enabled = false;
    this.retry = false;

    // Connect
    this.connect = function(address) {

        // Sets the address
        this.address = address;

        // Creates the websocket connection
        this.socket = new WebSocket(address);

        // On message event handler
        this.socket.onmessage = function(event) {

            // Do stuff here

        }

        this.socket.onopen = function(event) {

            // On connect, disable retry system
            window.ta.enabled = true;
            window.ta.retry = false;

        }

        this.socket.onclose = function(event) {

            // On close, enable retry system, disable bidding
            window.ta.enabled = false;
            window.ta.retry = true;
            window.ta.bidEnabled = false;

        }

        this.socket.onerror = function(event) {

            // Set variables off
            window.ta.enabled = false;
            window.ta.bidEnabled = false;
            window.ta.retry = true;

        }

        return true;
    }


    // Close Socket
    this.closeSocket = function() {

        // Shutdown websocket
        this.socket.close();
        return true;

    }

    // Send Message
    this.socketSend = function(content) {
        this.socket.send(content);
        return true;
    }

    // Retry System: Attempts to reconnect when a connection is dropped
    this.repeat = setInterval(function() {
        if (window.ta.enabled == false && window.ta.retry == true) {
            window.ta.connect(window.ta.address);
        }

    }, 2000);

}

window.ta = new WSWrapper();
window.ta.connect('wss://example.com');

我想出了一些想法和问题,任何答案都可以。

I have come up with some thoughts and questions, any answers would be good.


  1. 是否可以重新连接同一套接字?就像.open( url )函数会重新打开连接?我看了看Chrome控制台,浏览了WebSocket的原型,但是在那里什么都看不到,所以我认为不是,但还是希望被告知。

  1. Is there a way to reconnect the same socket? like an .open(url) function that will re-open the connection? I looked in the chrome console, and went through the prototype for the WebSocket, but I see nothing there, so I don't think so but would love to be told otherwise.

是否可以通过使用一些接收信息的函数来解决此问题,例如,我创建WebSocket实例,然后将所有请求传递给另一个函数来管理消息信息,然后当连接断开时,我可以以某种方式删除旧实例并重新创建一个新实例?

Could I fix this by using some functions that take the information, so for example, I create the WebSocket instance and then pass all requests to another function to manage the message information, and then when a connection disconnects, I can somehow delete the old instance and re-create a new one?

一切都会很好,因为我真的不确定,似乎每个人都做一个包装器(就像我正在做的那样),但是做的事情有所不同,所以什么是最好的方法还是首选的方法,它不会导致套接字的多个实例继续跑?如果我的代码有问题,请解释!

Anything would be good, as I am really not sure, it seems that everyone makes a wrapper (like I am doing), but does things differently, so what is the best way or the preferred way, that won't cause multiple instances of the socket to keep running? If there is a problem with my code then please explain!

谢谢

推荐答案

对此进行了更新,我能够采用以下代码:
https://github.com/websockets/ws/wiki/Websocket-client-implementation-for-auto-reconnect

just an update on this, I was able to take the following code: https://github.com/websockets/ws/wiki/Websocket-client-implementation-for-auto-reconnect

并修改它以在浏览器中为我工作。参见下面的代码,请记住,这是上面的改编,因此我在代码中不屑一顾。

And amend it to work for me in the browser. See the below code, remember this is an adaption from the above, so I take no credit in the code.

// Define WSClient instance
window.WSClient = {

    // Default reconnect interval
    reconnectInterval: 5000,

    // Define whether it has ever reconnected
    reconnected: false,

    // Log messages
    debug: false,

    // Open the URL
    open: function(url) {

        // Define that
        var that = this;

        // Open the URL
        this.url = url;

        // Create underlying websocket instance
        this.instance = new WebSocket(this.url);

        // Setup the event handler for onopen
        this.instance.onopen = function (ev) {

            // If it has ever reconnected lets say that
            if (that.reconnected && that.debug) {
                console.log('[WS]: Reconnected.');
            }

            // Run the open function
            that.onopen(ev);
        }

        // Setup the event handler for onmessage
        this.instance.onmessage = function(data, flags) {
            that.onmessage(data, flags);
        }

        // Setup the event handler for onclose
        this.instance.onclose = function(e) {
            switch (e){

                // Normal closure
                case 1000:
                    if (that.debug) {
                        console.log("[WS]: Closed");
                    }
                    break;

                // Abnormal closure
                default:
                    that.reconnect(e);
                    break;
            }

            // Run onclose event
            that.onclose(e);
        }

        // Setup the event handler for onerror
        this.instance.onerror = function(e) {
            switch (e.code){

                // Try and reconnect
                case 'ECONNREFUSED':
                    that.reconnect(e);
                    break;

                // Otherwise run error
                default:
                    that.onerror(e);
                    break;
            }
        }
    },

    // Setup send function
    sendRaw: function(data, option) {
        try {
            this.instance.send(data, option);
        } catch (e) {
            this.instance.emit('error', e);
        }
    },

    // Send the content
    send: function(content) {
        this.instance.send(content);
    },

    // Define the reconnection function
    reconnect: function(e) {

        // Define that
        var that = this;

        // Log reconnection
        if (that.debug) {
            console.log(`[WS]: Reconnecting in ${this.reconnectInterval / 1000} seconds.`);
        }

        // Set reconnect timeout
        setTimeout(function() {

            // Log reconnecting
            if (that.debug) {
                console.log("[WS]: Reconnecting...");
            }

            // Define has reconnected
            that.reconnected = true;

            // Try and open the URL
            that.open(that.url);

        }, this.reconnectInterval);
    },
}

所以我在Vue.JS框架中使用它像这样:

So I use this in the Vue.JS framework like so:

<script type="text/javascript">

    // Define the websocket
    window.vm['socket_example'] = new Vue({
        el: '#socket_example',
        name: 'SocketExample',
        data: {},
        methods: {

            // On connection open
            socket_open: function(event) {

                // Send get lots function
                this.$socket.send('some_content_here');

            },

            // On connection close
            socket_close: function(event) {

            },

            // On connection error
            socket_error: function(error) {

            },

            // On connection message
            socket_message: function(event) {

            },

        },

        mounted: function() {

            // Setup WebSocket connection
            this.$socket = WSClient;
            this.$socket.debug = true;
            this.$socket.open('<?php echo $endpoint; ?>');

            // Setup websocket listeners
            this.$socket.onopen = this.socket_open;
            this.$socket.onclose = this.socket_close;
            this.$socket.onerror = this.socket_error;
            this.$socket.onmessage = this.socket_message;

        },
    });
</script>

无论如何,我希望这会有所帮助!

Anyway I hope this was helpful!

这篇关于在不创建新实例的情况下重新连接WebSocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆