javascript - 简单的 websocket 库(这在通话中丢失)
问题描述
------注意:请参阅本文末尾的解决方案--------
我正在尝试制作一个简单的 websocket 库,它允许在连接时进行一次回调,在收到消息时进行一次回调,如果 5 秒后没有收到消息,则自动重新连接。
<html>
<script>
function ws(url, cb, concb){
this.timeout = setTimeout(this.timeoutCB, 5000);
this.url = url
this.cb = cb;
this.concb = concb;
this.startConnection()
}
ws.prototype.startConnection = () => {
this.conn = new WebSocket(this.url);
this.conn.onopen = () => {
this.concb()
console.log('Connected ');
}
this.conn.onclose = function() {
console.log('Connection closed ');
}
this.conn.onmessage = (e) => {
console.log('Received From Server: ' + e.data);
clearTimeout(this.timeout);
text = e.data;
this.cb(text);
this.timeout = setTimeout(this.timeoutCB, 5000);
}
}
ws.prototype.send = function(e) {
this.conn.send(e);
}
ws.prototype.timeoutCB = () => {
alert("PRESS OK TO RECONNECT");
this.timeout = setTimeout(this.timeoutCB, 5000);
this.startConnection();
}
w = new ws("127.0.0.1:9000", null, null);
</script>
</html>
我创建了一个startConnection
方法,以便能够在构造函数和timeoutCB
方法中调用它。问题是,当我this.startConnection
从构造函数调用时,这不是 ws 对象而是window
. 我不知道如何创建一个startConnection
可以从构造函数和另一个方法调用的方法,例如timeoutCB
- - - - - - - - - - 解决方案 - - - - - - - - - - - - - - - ----------------------
请查看尼克帕森斯的评论。这是应用他的建议后对我有用的代码:
function ws(url, cb, concb){
this.url = url
this.cb = cb;
this.concb = concb;
this.startConnection()
}
ws.prototype.startConnection = function() {
this.timeout = setTimeout(() => this.timeoutCB(), 5000);
console.log(this)
this.conn = new WebSocket(this.url);
this.conn.onopen = () => {
this.concb()
console.log('Connected ');
}
this.conn.onclose = () => {
console.log('Connection closed ');
}
this.conn.onmessage = (e) => {
console.log('Received From Server: ' + e.data);
clearTimeout(this.timeout);
text = e.data;
this.cb(text);
this.timeout = setTimeout(() => this.timeoutCB(), 5000);
}
}
ws.prototype.send = function(e) {
this.conn.send(e);
}
ws.prototype.timeoutCB = function() {
alert("PRESS OK TO RECONNECT");
this.startConnection();
}
解决方案
推荐阅读
- java - 重用 javax.jms.BytesMessage
- javascript - NgIf 有时使用 2 条件无法正常工作
- ios - GADAppOpenAd 返回错误 Domain=com.google.admob Code=11“请求错误:内部错误。”
- c# - 表 - 使用角度存储过程中的数据的高图表行
- excel - 在 Excel IF 函数中获取#VALUE ERROR
- r - RStudio:如何在 cite-key 中使用特殊符号引用 bibtex 参考
- android - 将对齐设置为段落跨度以编辑文本
- ruby-on-rails - 安装推荐 gem 时出错 - 无法构建 gem 原生扩展(hiredis.h 没有这样的文件或目录)
- python - 我不确定如何解决这个问题,它说 f 没有定义
- powerbi - Power BI 模型大小限制