ES6类中的Nodejs Websocket连接

时间:2019-06-27 14:03:22

标签: node.js ecmascript-6 websocket callback

我不确定这是否是在NodeJS中实现websocket连接的正确方法,但是我遇到的问题不是WebSockets,而是类变量。

这是我的WebSocketClass:

class WebSocketCalss { 

    constructor ( httpserver )
    {
        console.log("Initializing WebSocketCalss");
        this.httpServer = httpserver;
        this.connection = null;
        this.client = null;
        this.initializeWebSocket();
    }

    initializeWebSocket()
    {
        var WebSocketServer = require('websocket').server;

        var wsServer = new WebSocketServer({
            httpServer: this.httpServer
        });

        wsServer.on('request', function(request) {
            console.log((new Date()) + ' Connection from origin ' + request.origin + '.');
            this.connection = request.accept(null, request.origin); 
            console.log((new Date()) + ' Connection accepted.');
            this.connection.sendUTF(JSON.stringify({ type: "history", data: "data"} ));
            var t = 0;

            /* ---- Client ---- */
            var W3CWebSocket = require('websocket').w3cwebsocket;
            this.client = new W3CWebSocket('wss://ws.bitstamp.net');

            this.client.onerror = function() {
                console.log('Connection Error');
            };

            this.client.onopen = function() {
                console.log('WebSocket Client Connected');
                var subscribeMsg = {
                    "event": "bts:subscribe",
                    "data": {
                        "channel": "live_trades_btcusd"
                    }
                };
                this.client.send(JSON.stringify(subscribeMsg));
            };

            this.client.onclose = function() {
                console.log('echo-protocol Client Closed');
            };

            this.client.onmessage = function(e) {
                if (typeof e.data === 'string') {
                    var bitstampPrice = JSON.parse(e.data).data.price;
                    console.log(bitstampPrice);

                    this.connection.sendUTF(bitstampPrice);
                }
            };
            });



        //this.connection.sendUTF(JSON.stringify({ type: "history", data: "data"} ));
    }

}

module.exports = (httpserver) => { return new WebSocketCalss(httpserver) }

也许是毛茸茸的,所以这就是我想要做的:

  • 我的NodeJS服务器将打开一个到我的客户端(浏览器)的WebSocket连接
  • 在此WebSocket中,我要发送从另一个WebSocket接收到的值(即,我的NodeJS将作为客户端连接)
  • 似乎一切正常,但是,当我尝试将值(作为客户端收到的)发送到自己的客户端(因为我是服务器)时,我得到了
  

无法读取未定义的属性“发送”

基本上,在回调内部,此变量未定义。好像这是一个新对象。 我不熟悉ES6,所以我认为我做的事情根本上是错误的。 如果有人可以对此有所了解,将不胜感激。

1 个答案:

答案 0 :(得分:2)

this内使用function()时,this的上下文绑定到function而不是外部类。

this.client.onopen = () => {
    console.log('WebSocket Client Connected');
    var subscribeMsg = {
        "event": "bts:subscribe",
        "data": {
            "channel": "live_trades_btcusd"
        }
    };
    this.client.send(JSON.stringify(subscribeMsg));
};