我不确定这是否是在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) }
也许是毛茸茸的,所以这就是我想要做的:
无法读取未定义的属性“发送”
基本上,在回调内部,此变量未定义。好像这是一个新对象。 我不熟悉ES6,所以我认为我做的事情根本上是错误的。 如果有人可以对此有所了解,将不胜感激。
答案 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));
};