4 months 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
3 Replies
4 months 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[bot] • 4 months 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
4 months 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[bot] • 4 months ago
4 months 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[bot] • 4 months ago
Status changed to Closed brody • 4 months ago