首页 > 解决方案 > 简单的 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();
    }

标签: javascriptclasswebsocketthisprototype

解决方案


推荐阅读