Monday, 17 May 2021

Use express as proxy for websocket

I have a data provider which gives me stock prices via TCP connection. The data provider only allows a static IP to connect to their service.

But since I need to format the data before sending it to my front-end I want to use my express back-end as a proxy.

What that means is:

  • I need to connect my back-end to my data provider via websocket(socket.io) in order to get the data (back-end acts as client)
  • I need my back-end to broadcast this received data to my front-end(back-end acts as server)

My question is: Is that possible at all? Is there an easier way to achieve this? Is there a documentation on how to use an express app as websocket server and client at once?


EDIT:

I got this working now. But my current solution kills my AWS EC2 instance because of huge CPU usage. This is how I've implemented it:

const net = require('net');
const app = require('express')();
const httpServer = require('http').createServer(app);

const client = new net.Socket();

const options = {
  cors: {
    origin: 'http://someorigin.org',
  },
};

const io = require('socket.io')(httpServer, options);

client.connect(1337, 'some.ip', () => {
  console.info('Connected to some.ip');
});

client.on('data', async (data) => {
  // parse data
  const parsedData = {
    identifier: data.identifier,
    someData: data.someData,
  };

  // broadcast data
  io.emit('randomEmitString', parsedData);
});

client.on('close', () => {
  console.info('Connection closed');
});

httpServer.listen(8081);

Does anyone have an idea why this causes a huge CPU load? I've tried to profile my code with clinicjs but I couldn't find a apparent problem.



from Use express as proxy for websocket

No comments:

Post a Comment