Can't connect to websocket
mevwebdev
TRIALOP

a year ago

I cannot connect to websocket server

Backend code:

const http = require("http");

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

server.listen(process.env.PORT, () => {
  console.log(
    `WebSocket server started on ws://localhost:${process.env.PORT || 8080}`
  );
});

Frontend code:

const { messages, sendMessage, onlineUsers } = useWebSocket(
    "wss://gymapp-backend-production.up.railway.app"
  );

It works when I run backend locally

Closed

3 Replies

a year ago

Hello,

You are starting your HTTP and WS servers on different ports, you need to start them both on the same port, and you need to specify a subpath like /ws to handle the WebSocket connection.

Best,

Brody


Status changed to Awaiting User Response Railway over 1 year ago


brody

Hello, You are starting your HTTP and WS servers on different ports, you need to start them both on the same port, and you need to specify a subpath like `/ws` to handle the WebSocket connection. Best, Brody

mevwebdev
TRIALOP

a year ago

app.listen(process.env.PORT || 3001, () => {
  console.log(`Server is running`);
});

I use process.env.PORT on both http and websocket so I don't understand how I run them on different ports.

Also I have ws handling

wss.on("connection", (ws: any) => {
  console.log("New client connected");
  usersOnline.add(ws);
  broadcastUserCount();

  ws.on("message", (message: any) => {
    wss.clients.forEach((client: any) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });

  ws.on("close", () => {
    console.log("Client disconnected");
    usersOnline.delete(ws);
    broadcastUserCount();
  });
});

Status changed to Awaiting Railway Response Railway over 1 year ago


a year ago

You can see that two ports are being listened on -

You need to start them both on the same port, and you need to specify a subpath like /ws to handle the WebSocket connection.

Unfortunately, we cannot help here further as this is turning into coding support, we cannot offer coding support here, we can only offer support for the Railway platform or product.

Best,

Brody

Attachments


Status changed to Awaiting User Response Railway over 1 year ago


Status changed to Closed brody over 1 year ago


Welcome!

Sign in to your Railway account to join the conversation.

Loading...