I am trying to learn how websockets work. I am able to get trading data from a websocket server and print it on the console. However, I am trying to understand how I can pass that message into my websocket server so that I can send it to my websocket clients. Basically, I want to print each message on browser.
"use strict";
const WebSocket = require("ws");
const binanceWS = new WebSocket("wss://stream.binance.com:9443/ws/stratbtc@trade");
binanceWS.on("open", function open() {
console.log("open action");
});
binanceWS.on("message", function incoming(data) {
console.log(data);
});
Now this binanceWS will print data when it recieves one. The thing I am trying to do is how I can pass to the send eventlistener of my WebSocket.Server object. As you can see an example from https://github.com/websockets/ws wss itself takes a websocket object when there is a connection.
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
Thanks!
NOTE: The structure I am talking about is like this. Basically, I will have websocket consumers to get trade data. And within same host (localhost for now) there will be a websocket server. This websocket server will send data to each client websockets.
SUCCESS:
Ok I made it by defining consumer websocket (binanceWS) message listener in websocket server connection. I am not sure if this is a good way though
"use strict";
const WebSocket = require("ws");
const binanceWS = new WebSocket("wss://stream.binance.com:9443/ws/stratbtc@trade");
binanceWS.on("open", function open() {
console.log("open action");
});
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
binanceWS.on("message", function incoming(data) {
ws.send(data);
});
});
