Websocket从函数

时间:2016-01-29 10:46:29

标签: javascript websocket

我试图为我的应用程序使用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

问题是什么?

3 个答案:

答案 0 :(得分:3)

您是否应该等待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');

答案 1 :(得分: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');
});

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

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

答案 2 :(得分:1)

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

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