I try to use the following code to connect a 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();
});
unfortunately when onOpen is called socket seems to be undefined. I first thought maybe the socket is closed right after onOpen, but onClose is never called and onError is also never called.
What is my mistake?