3

I have #NestJS server running on herokou.com and a react CRA app running on vercel.com I am trying to connect the frontend and backend with websockets (socket.io) However the connection is not getting made. In the console the network requests show up no error, but the GET requests corresponding to socket.io timeout. There is no response. This is how nestjs gateway is written. I can see the log of the gateway getting initialized. However no log of connection/disconnection even when i try to open up clients.

@WebSocketGateway()
export class AppGateway
  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
  users: Record<string, any> = {};
  @WebSocketServer() server;
  afterInit(server: any) {
    this.logger.log('Initialized');
  }
  handleConnection(client: any, ...args: any[]) {
    console.log('connected.');
    if (!this.users[client.id]) {
      this.users[client.id] = client.id;
    }
    client.emit('yourID', client.id);
    this.server.emit('allUsers', this.users);
  }

In the client i am connect like this

    socket.current = io.connect(
      "https://server.herokuapp.com:" + props.port
    );

I have checked props.port is fine. Just that the GET requests in the network requests of developer tools window, time out, there is no response. Example: https://server.herokuapp.com:43030/socket.io/?EIO=3&transport=polling&t=NAq8j0w This GET responds nothing and timeout.

2 Answers2

0

If someone will be useful:

For deploying on Heroku you can use only one port and Heroku decides what is port it will be, you need only use process.env.PORT.

This might help you:

link1 - Reddit - Port number for Socket.io with Express on Heroku

link2 - Stackoverflow - How To Make Socket Connection To Heroku Server In Socket.io?

link3 - Stackoverflow - Heroku + node.js: I have a server which uses multiple ports. How can I get Heroku to allocate them?

Serafim
  • 353
  • 3
  • 10
-1

I think in the client-side, the way to initilize the socket.io is by

import io from "socket.io-client";

const socket = io("http://DOMAIN:IP"); // or https

or if you want it in a react Ref hook:

const socket = useRef();
socket.currect = io("http://DOMAIN:IP");  // or https

or in one line I think: const socket = useRef(io("http://DOMAIN:IP")); // or https

Shani Kehati
  • 427
  • 5
  • 10