tiagosiebler / binance

Node.js & JavaScript SDK for Binance REST APIs & WebSockets, with TypeScript & browser support, integration tests, beautification & more.
MIT License
758 stars 266 forks source link

[question] How to return the data received by websocket to the front-end project #369

Closed gaozhao7 closed 8 months ago

gaozhao7 commented 11 months ago

Hello, I introduced binance in the express project, and it works well in the project. I would like to know how I need to push the data returned by websockets through the wsClient.subscribeSpotKline request to my front-end project? It is to push through another socketio link, but I have encountered the problem: I don't know how to get the socket of socketio in the websockets to push the information. Is there a better way to achieve my needs? (Translation through the translation tool, please bear with me if there is any incorrect place, thank you!)

tiagosiebler commented 8 months ago

Some exchanges allow you to directly connect to websockets from a frontend context. Those that weren't designed for it though, they will give you a CORS error. In those cases you will typically need to host your websocket consumers in a backend server, and pass it to the frontend yourself (exactly what you're asking).

There's a lot of tools around for exactly that - streaming data from backend to frontend. Graphql has "subscriptions". A common choice if you're already using graphql for your "rest api" needs:

You can also host your own websocket for this step, either using ws or one of the many other libraries out there on npm and github for websockets. I'm sure socketio has docs too on hosting your own websocket server for your frontend to connect to. Essentially you would then build a "bridge", which connects incoming events to your own websocket server, so any connected frontend clients also receive the events downstream.