【问题标题】:WebSocket is Null after onOpenonOpen 后 WebSocket 为 Null
【发布时间】: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


    【解决方案1】:

    您正在丢失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 来引用套接字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      相关资源
      最近更新 更多