【发布时间】:2014-09-28 11:22:14
【问题描述】:
我尝试使用以下代码连接 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 时,socket 似乎是未定义的。我首先认为可能套接字在 onOpen 之后立即关闭,但从未调用过 onClose,也从未调用过 onError。
我的错误是什么?
【问题讨论】:
标签: javascript websocket