mg12345
mg12345

Reputation: 1

Multiple services using pm2 with Websockets on Azure Linux Web App, which ports?

I'm working on creating a WebApp using React and Websockets building it of from this example here: https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-live-data-visualization-in-web-apps

Locally everything is working fine. I have the React frontend code in a separate folder as well as the websocketserver code.

I'm trying to both into a single Azure Linux Web App (Basic tier not free) and starting it up with pm2 and this ecosystem.config.js:

module.exports = {
  apps : [
      {
        name : "frontend",
        script : "serve",
        env: {
          PM2_SERVE_PATH: './frontend/build',
          PM2_SERVE_SPA: 'true',
        }
      },
      {
        name   : "websocketserver",
        script : "./websocketserver/server.js",
      }
  ]
}

Both services are starting up correctly but the websocket connection is unable to connect.

The server in server.js looks like this:

const server = http.createServer();
const wss = new WebSocket.Server({ server });

wss.broadcast = (data) => {
  if (wss.clients.size === 0) {
    console.log(`No clients connected. Broadcasting over port ${server.address().port}`);
    // console.log(`No clients connected. Broadcasting over port ${wss.options.port}`);

  } else {
    wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        try {
          console.log(`Broadcasting data ${data}`);
          client.send(data);
        } catch (e) {
          console.error(e);
        }
      }
    })
  }
};

server.listen('8081', () => {
  console.log('Listening on %d.', server.address().port);
});

If I use process.env.PORT || '3000' in server.listen(), then I get an EAINUSE error as it conflicts with the frontend 8080 port, so I handpicked 8081.

I have not found any useful article about this. Can anybody help and advice what to try?

Thanks!

Upvotes: 0

Views: 390

Answers (2)

Carnegie Johnson
Carnegie Johnson

Reputation: 9

Set the PORT environment variable respective value in your App Service config, ref https://learn.microsoft.com/en-us/azure/app-service/configure-language-nodejs

Upvotes: 0

Harshitha Veeramalla
Harshitha Veeramalla

Reputation: 1753

  • I have followed the given documentation and able to get the desired result accordingly after changing the PORT to 8081.

  • Initially with PORT 3000, I got the below error.

enter image description here

  • I have changed the PORT to 8081 in server.js.

enter image description here

  • After changing the PORT you need to set IotHubConnectionString and EventHubConsumerGroup once again and run npm install and npm start

  • Please follow the document correctly and check once again. enter image description here

enter image description here

Upvotes: 0

Related Questions