title: websockets - get message from a websocket server and send it to client
body: <p>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.</p>
  
  <pre><code>"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);
  });
  </code></pre>
  
  <p>Now this <code>binanceWS</code> will print data when it recieves one. The thing I am trying to do is how I can pass to the <code>send</code> eventlistener of my WebSocket.Server object. As you can see an example from <a href="https://github.com/websockets/ws" rel="nofollow noreferrer">https://github.com/websockets/ws</a> wss itself takes a websocket object when there is a connection.</p>
  
  <pre><code>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');
  });
  </code></pre>
  
  <p>Thanks!</p>
  
  <p><strong>NOTE</strong>: 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.</p>
  
  <p><a href="https://i.stack.imgur.com/mw976.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mw976.png" alt="enter image description here"></a></p>
  
  <p><strong>SUCCESS</strong>:
  Ok I made it by defining consumer websocket (<code>binanceWS</code>) <code>message</code> listener in websocket server connection. I am not sure if this is a good way though</p>
  
  <pre><code>"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);
    });
  });
  </code></pre>