You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have a MERN stack app deployed on aws ec2 ubuntu machine. (https://game-hub.duckdns.org/).
I have my frontend on PORT 8080 and backend services on PORT 3000-3007.
2 of my backend services uses socket.io.
I have used nginx for port forwarding and ssl for https.
My socket io are working fine in local machine.
Can you please tell why websocket is not working.
useEffect(() => {
// Listen for game start
socket.on("gameStart", ({ players }) => {
setBoard(Array(9).fill(null));
setWinner("");
setRematchRequested(false);
if (players[0].userId === selfUserId) {
setSelfUserRole(players[0].role);
setOpponentUserId(players[1].userId);
} else {
setSelfUserRole(players[1].role);
setOpponentUserId(players[0].userId);
}
if (players[0].role === "O") {
setPlayingTurn(players[0].userId);
} else {
setPlayingTurn(players[1].userId);
}
setGameStarted(true);
});
// Listen for game updates
socket.on("gameUpdate", (game) => {
setBoard(game.board);
setPlayingTurn(game.currentPlayer);
});
// Listen for game over
socket.on("gameOver", ({ winner }) => {
setWinner(winner);
});
return () => {
socket.off("gameStart");
socket.off("gameUpdate");
socket.off("gameOver");
};
}, [selfUserId, opponentUserId]);
This is one service
import express from "express";
import cors from "cors";
import router from "./routes/index.js";
import { PORT } from "./config/index.js";
import { connectWithDB, socketHandler } from "./utils/index.js";
import { Server as SocketIO } from "socket.io";
const app = express();
// TODO Configure this later
app.use(cors());
// TODO Add Limit on this
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use("/", router);
const server = app.listen(PORT, async () => {
console.log("Listening on port: ", PORT);
// Verify access token and get userId
const userId = await verifyAccessTokenForSocket(accessToken);
if (!userId) {
return callback({ error: true, message: "Access Token Error" });
}
// Join the room with id = userId
socket.join(userId);
callback({ error: false, message: Joined room ${userId} });
});
socket.on("send-message", async (data, callback) => {
const { messageContent, accessToken, otherUserId } = data;
const senderId = await verifyAccessTokenForSocket(accessToken);
if (!senderId) {
return callback({ error: true, message: "Access Token Error" });
}
try {
await chatService.sendMessage(
senderId,
otherUserId,
messageContent
);
io.to(otherUserId).emit("receive-message", {
senderId,
messageContent,
timestamp: new Date()
});
callback({ error: false });
} catch (error) {
console.error("Error sending message:", error.message);
callback({ error: true, message: "Sending Message Error" });
}
});
socket.on("disconnect", () => {
// TODO - Can be use for updating user online status and last active status
});
});
};
export default socketHandler;
This is other service's backend code
import express from "express";
import { PORT } from "./config/index.js";
import cors from "cors";
import router from "./routes/index.js";
import { Server as SocketIO } from "socket.io";
import socketHandler from "./utils/socketHandler.js";
const app = express();
const initializeServer = () => {
// TODO Configure this later
app.use(cors());
// TODO Add Limit on this
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use("/", router);
};
const server = app.listen(PORT, async () => {
initializeServer();
console.log("Listening on port: ", PORT);
});
// TODO Configure this CORS later
const io = new SocketIO(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
socketHandler(io);
import verifyAccessTokenForSocket from "./verifyAccessTokenForSocket.js";
import generateGameId from "./generateGameId.js";
import checkWinner from "./checkWinner.js";
import updateScore from "./updateScore.js";
let games = {};
let activeGames = {};
setInterval(() => {
const now = Date.now();
for (const gameId in activeGames) {
if (now - activeGames[gameId].createdAt > 10 * 60 * 1000) {
console.log(Game ID ${gameId} expired due to inactivity);
delete activeGames[gameId];
}
}
for (const gameId in games) {
if (now - games[gameId].createdAt > 10 * 60 * 1000) {
console.log(Game ID ${gameId} expired due to inactivity);
delete games[gameId];
}
}
}, 60 * 1000);
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
I have a MERN stack app deployed on aws ec2 ubuntu machine. (https://game-hub.duckdns.org/).
I have my frontend on PORT 8080 and backend services on PORT 3000-3007.
2 of my backend services uses socket.io.
I have used nginx for port forwarding and ssl for https.
My socket io are working fine in local machine.
Can you please tell why websocket is not working.
When I am writing
export const CHAT_SERVICE_SOCKET_URL = "http://game-hub.duckdns.org:3005";
The ws is working fine.
But,
export const CHAT_SERVICE_SOCKET_URL = "https://game-hub.duckdns.org/backend/chat";
is not working
Below is my nginx config-
server {
server_name game-hub.duckdns.org www.game-hub.duckdns.org;
Chat Service
Frontend
}
server {
if ($host = www.game-hub.duckdns.org) {
return 301 https://$host$request_uri;
} # managed by Certbot
}
This is my frontend's code
export const CHAT_SERVICE_SOCKET_URL = "https://game-hub.duckdns.org/backend/chat";
// export const CHAT_SERVICE_SOCKET_URL = "http://localhost:3005/backend/chat"; // Dev
export const TICTACTOE_SOCKET_URL = "https://game-hub.duckdns.org/backend/tictactoe";
import { io } from "socket.io-client";
import { CHAT_SERVICE_SOCKET_URL } from "./constant";
const socket = io(CHAT_SERVICE_SOCKET_URL);
export default socket;
import { io } from "socket.io-client";
import { TICTACTOE_SOCKET_URL } from "./constant";
const socket = io(TICTACTOE_SOCKET_URL);
export default socket;
import { useEffect, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import socket from "../../../utils/getChatSocket";
import { receiveMessage } from "../../../config/chatSlice";
import { toast } from "react-toastify";
let isChatRoomActive = false;
const useChatRoom = () => {
const accessToken = useSelector((state) => state.userDataSlice.accessToken);
const dispatch = useDispatch();
const cleanupRef = useRef(false);
};
export default useChatRoom;
useEffect(() => {
// Listen for game start
socket.on("gameStart", ({ players }) => {
setBoard(Array(9).fill(null));
setWinner("");
setRematchRequested(false);
This is one service
import express from "express";
import cors from "cors";
import router from "./routes/index.js";
import { PORT } from "./config/index.js";
import { connectWithDB, socketHandler } from "./utils/index.js";
import { Server as SocketIO } from "socket.io";
const app = express();
// TODO Configure this later
app.use(cors());
// TODO Add Limit on this
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use("/", router);
const server = app.listen(PORT, async () => {
console.log("Listening on port: ", PORT);
});
// TODO Configure this CORS later
const io = new SocketIO(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
socketHandler(io);
process.on("unhandledRejection", (err) => {
console.log(Unhandled rejection ${err.name} occurred);
server.close(() => {
process.exit(1);
});
});
import chatService from "../services/chatService.js";
import verifyAccessTokenForSocket from "./verifyAccessTokenForSocket.js";
const socketHandler = (io) => {
io.on("connection", (socket) => {
socket.on("join-room", async (data, callback) => {
const { accessToken } = data;
};
export default socketHandler;
This is other service's backend code
import express from "express";
import { PORT } from "./config/index.js";
import cors from "cors";
import router from "./routes/index.js";
import { Server as SocketIO } from "socket.io";
import socketHandler from "./utils/socketHandler.js";
const app = express();
const initializeServer = () => {
// TODO Configure this later
app.use(cors());
};
const server = app.listen(PORT, async () => {
initializeServer();
console.log("Listening on port: ", PORT);
});
// TODO Configure this CORS later
const io = new SocketIO(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
socketHandler(io);
import verifyAccessTokenForSocket from "./verifyAccessTokenForSocket.js";
import generateGameId from "./generateGameId.js";
import checkWinner from "./checkWinner.js";
import updateScore from "./updateScore.js";
let games = {};
let activeGames = {};
setInterval(() => {
const now = Date.now();
for (const gameId in activeGames) {
if (now - activeGames[gameId].createdAt > 10 * 60 * 1000) {
console.log(Game ID ${gameId} expired due to inactivity);
delete activeGames[gameId];
}
}
for (const gameId in games) {
if (now - games[gameId].createdAt > 10 * 60 * 1000) {
console.log(Game ID ${gameId} expired due to inactivity);
delete games[gameId];
}
}
}, 60 * 1000);
const socketHandler = (io) => {
io.on("connection", (socket) => {
socket.on("createGame", async ({ accessToken }, callback) => {
const userId = await verifyAccessTokenForSocket(accessToken);
if (!userId) {
return callback({ error: true, message: "Access Token Error" });
}
const gameId = generateGameId(activeGames);
activeGames[gameId] = {
createdAt: Date.now(),
players: [{ userId, role: null, readyForRematch: false }]
};
socket.join(gameId);
callback(gameId);
});
};
export default socketHandler;
Nothing is getting logged on console in prod and everything is working as expected in dev environment
Only long polling is ongoing which is also not working
No firewall is enables
Beta Was this translation helpful? Give feedback.
All reactions