respectabiggle
respectabiggle

Reputation: 51

In Node/Express, can I connect to an external data API stream with a websocket, and then pass that stream between my server and client files?

My app currently connects to the same data stream API twice, once from server.js and once from client.js. This seems inefficient.

example: wss://stream.example.com:5555/ws/GMT4@weatherdata (pushes data)

Is it possible to pass an externally-sourced data stream between server.js and client.js?

Thank you.

Edit:
I've added one solution in the comments.
Is there any room for improvement? Thanks again.

Upvotes: 1

Views: 568

Answers (1)

respectabiggle
respectabiggle

Reputation: 51

Edit: thanks to some help from socket.io, this method works:

Github repo

dependencies

socket.io
socket.io-client
ws
express

index.html

<body>
    <script src="../socket.io/socket.io.js"></script>
</body>

client.js

const socket = io();

socket.on('channel1', (foo) => {
    console.log(foo);                                            
});

server.js

const express = require('express');
const app = express();
const server = require('http').createServer(app); 
server.listen(3000, () => console.log("Express Running on PORT 3000")); 
app.use(express.static('public'));

const { Server } = require('socket.io'); 
const io = new Server(server);      

const { WebSocket } = require('ws');
const client = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@trade');

client.on('message', (event) => {
    let parse = JSON.parse(event); 
    let data = parseFloat(parse.p)
    // console.log(data)          
    io.emit('channel1', data);   
});

Upvotes: 0

Related Questions