我尝试使用以下代码连接Websocket:
var sConn = {
socket: null,
uri: "ws://" + window.location.host + "/socket/",
init: function() {
this.socket = new WebSocket(this.uri);
this.socket.onopen = this.onOpen;
this.socket.onclose = this.onClose;
this.socket.onerror = this.onError;
this.socket.onmessage = this.onMessage;
},
onOpen: function(){
console.log(this.socket); // prints "undefined"
this.socket.send("Hello Server!"); // can't read property send of undefined
},
onClose: function(event){
console.log("Close:",event); // is never called
},
onError: function(err){
console.log("Error:",err); // also never called
},
onMessage: function(msg){
console.log("Got Message:",msg);
}
};
$(document).ready(function(){
sConn.init();
});
不幸的是,在调用onOpen时,套接字似乎未定义。我首先想到也许是在onOpen之后立即关闭套接字,但是永远不会调用onClose,也永远不会调用onError。
我怎么了
最佳答案
您正在丢失init()
中的绑定上下文。
尝试将其重写为此:
init: function() {
this.socket = new WebSocket(this.uri);
this.socket.onopen = this.onOpen.bind(this);
this.socket.onclose = this.onClose.bind(this);
this.socket.onerror = this.onError.bind(this);
this.socket.onmessage = this.onMessage.bind(this);
}
这样可以确保
sConn
中的所有事件处理函数均在正确的this
上下文中运行。或者,您可以使用
sConn.socket
而不是this.socket
引用套接字。关于javascript - onOpen后WebSocket为Null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26084366/