gpt4 book ai didi

javascript - onOpen后WebSocket为空

转载 作者:行者123 更新时间:2023-11-28 00:57:17 25 4
gpt4 key购买 nike

我尝试使用以下代码来连接 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() 中的绑定(bind)上下文。

尝试将其重写为:

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为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26084366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com