4

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.

enter image description here

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);
  });
});

2 Answers 2

3

I achieved this my keeping a global list for websocket clients. And when consumer websocket message event is triggered, it sends every client by traversing list.

"use strict";

const WebSocket = require("ws");

const binanceWS = new WebSocket("wss://stream.binance.com:9443/ws/eosbtc@trade");

var websocketList = [];

binanceWS.on("open", function open() {
    console.log("open action");
});

binanceWS.on("message", function incoming(data) {
    console.log(data);

    // send data to every websocket client
    websocketList.forEach(ws => {
        ws.send(data);
    });
});

const wss = new WebSocket.Server({ port: 8080 });

wss.on("connection", function connection(ws) {

    // add ws handle to websocket list.
    websocketList.push(ws);

    ws.on("close", function close() {
        console.log("Disconnected");
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Could you please post your client side? I would want to understand how the items in websocketList is retrieved on the client side?
A little late but... you shouldn't have the need to keep the clients list, according to the documentation (github.com/websockets/ws#server-broadcast) you should have the list of connected clients inside wss, which you can use to loop.
1

single websocket

//websocket connection event will return a socket you can later use
binanceWS.on("connection", function(socket) {
    socket.on("message", function incoming(data) {
    console.log(data);
    // if you want to send that message back to the client who sent it, 
    // you can use send method on the socket
     socket.send(data)
    });
});

Nesting websocket

//websocket connection event will return a socket you can later use
binanceWS.on("connection", function(socket) {
    // create another websocket here
    const wss = new WebSocket.Server({ port: 8080 });

    // connect the second websocket
     wss.on("connection", function(ws) {
      // start listening to first websocket incoming messages 
      // if second communication has successully been instantiated 
      socket.on("message", function incoming(data) {
      // send the data using the second websocket
      ws.send(data)
      })
    });
});

Then you need to have this minimum code in your client and you will see the interaction between the server and your client

client

const socket = new WebSocket('server_url'); // Connection opened 
socket.addEventListener('message', function (event) { socket.send('send message'); });

Note: Since you will use the incoming data of a websocket into another, it is best to open the second websocket only if the first one has successfully been opened

7 Comments

Please correct me if I am wrong. Here you are expecting a client websocket connecting to binanceWS. After a connection is established the client websocket can send message to binanceWS and binanceWS will send that message back?
Yes, that's it!
Thanks for your response but I am kinda confused. I am trying to send data when binanceWS.on('message') is triggered. And for this I need to create a new WebSocket.Server and use that websocket server object to send messages
Actually my piece of code will send data back to the client when message event is triggered. It means that on your client, you should have something like this: const socket = new WebSocket('server_url'); socket.addEventListener('message', function (event) { socket.send('send message'); }); I will update my answer
Hey edkeveked I updated my post with a small structure that I am trying to accomplish. Based on my structure binanceWS a consumer websocket that gets data from an exchange. Then I need to create a websocket server which will send the data I am getting from binanceWS to the client websockets. Was it clear? Thanks!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.