im 尝试为我的应用程序使用 Websocket
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
问题出在哪里?
你不应该等待正确的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');
您是否在等待调用.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');
};
您应该先等待套接字连接。Websocket 构造函数是非阻塞的,这意味着当您创建新的 Websocket 时,它会在后台连接,并且您的代码将继续。您需要在 Websocket 上将 onopen
属性设置为将在 Websocket 连接时执行的回调。
在这里,您可以看到它是如何完成的,您可以侦听哪些事件。