【问题标题】:Websocket return from functionWebsocket从函数返回
【发布时间】:2016-01-29 10:46:28
【问题描述】:

我正在尝试为我的应用程序使用 websockets

function Connector()
{
  this.protocol = "bla";
  this.socket   = new WebSocket("ws://echo.websocket.org", this.protocol);
}

Connector.prototype.emit = function()
{
  this.socket.send('abc');
}

对我来说可以调用:

var con = new Connector();
con.emit();

从我的浏览器控制台但从源代码我收到以下错误消息

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

有什么问题?

【问题讨论】:

    标签: javascript websocket


    【解决方案1】:

    您不应该等待readyState 的正确值吗?

    function Connector(wsurl) {
        this.protocol = "bla";
        this.socket = new WebSocket(wsurl, this.protocol);
    }
    Connector.prototype.emit = function(msg) {
    
        var self = this;
    
        (function _waitForSocketConnection(callback) {
            setTimeout(function() {
                if (self.socket.readyState === 1) {
                    console.log("Connection is made")
                    if (callback != null) {
                        callback();
                    }
                    return;
    
                } else {
                    console.log("wait for connection...")
                    _waitForSocketConnection(callback);
                }
            }, 5);
        })(function() {
            console.log("message sent!!!");
            self.socket.send(msg);
        });
    }
    
    
    var con = new Connector("ws://echo.websocket.org");
    con.emit('abc');
    //or even worst
    new Connector("ws://echo.websocket.org").emit('def');
    

    【讨论】:

    【解决方案2】:

    您在等待调用.onopen 函数吗?您应该仅在建立连接后才在 websocket 上发送消息。你可以试试类似

        function Connector() {
            this.protocol = "bla";
            this.socket   = new WebSocket("ws://echo.websocket.org", this.protocol);
            this.connected = false;
        }
        Connector.prototype.emit = function() {
    
            if(this.connected) {
                try {
                    this.socket.send('abc');
                    return true;
                }
                catch(err) {
                    console.log('Error' + err.message);
                    return false;
                }       
            }
            else {
                console.log('CRITICAL Error No WS');
                return false;
            }
        }
    
        con.socket.onopen = function() {
            console.log("webSocket Connected");
            con.connected = true;
            //send message here
            con.emit();
        };
        con.socket.onclose = function(e) {
            //closed
            con.connected = false;
        };
        con.socket.onerror = function(e) {
            console.log("Error",e);
        };
        con.socket.onmessage = function(msg) {
            //msg
        }
    

    更新代码

    function Connector(protocol, cB){
        var self = this,
            this.protocol = protocol,
            this.socket   = new WebSocket("ws://echo.websocket.org", this.protocol),
            this.connected = false;    
    
        this.socket.onopen = function() {
            self.connected = true;
            cB();
        };
    
        this.socket.onclose = function(e) {
            self.connected = false;
            //closed, inform(event)
        };
    
        this.socket.onerror = function(e) {
            //error, inform(event)
        };
    
        this.socket.onmessage = function(msg) {
            //msg, inform(event)
        }
    }
    
    Connector.prototype.emit = function(msg) {
        if(this.connected) {
            try {
                this.socket.send(msg);
                return true;
            }
            catch(err) {
                console.log('Error' + err.message);
                return false;
            }       
        }
        else {
            console.log('CRITICAL Error No WS');
            return false;
        }
    }
    
    var con = new Connector('blah',function() {
        con.emit('abc');
    });
    

    以及没有构造函数或任何其他事件的最简单情况;只是简单/基本的 ws 客户端

    var socket   = new WebSocket("ws://echo.websocket.org", 'bla');
    socket.onopen = function() {
        socket.send('msg');
    };
    

    【讨论】:

    • 对于“开始”的问题好多了,但是如果他在连接死后调用 emit() 怎么办?
    • @Gavriel :我试图快速合并...感谢提示:)
    • @Oxi 从实例设置 onXXX 方法似乎不是一个非常糟糕的主意???...您应该为每个实例编写 em...甚至重复 connected 绝对应该是私有的......不仅,你应该在创建实例之后编写 em!!!......
    • @Oxi ...ohhh 老兄....谢谢你的反对票...而不是进行建设性的讨论...您只是点击一下就跑了。我敢打赌不是第一次你错过了学习的机会......祝你好运!!!
    • @fedeghe:我已经更新了我的答案。增加了两个代码示例
    【解决方案3】:

    您应该先等待套接字连接。 Websocket 构造函数是非阻塞的,这意味着当您创建一个新的 Websocket 时,它会在后台连接并且您的代码会继续运行。你需要在你的 Websocket 上设置一个 onopen 属性,以在 Websocket 连接时执行回调。

    Here你可以看到它是如何完成你可以监听的事件的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-15
      • 2016-08-28
      • 2019-10-11
      • 2018-10-06
      • 2021-12-09
      • 2015-01-26
      相关资源
      最近更新 更多