Skip to content

Commit

Permalink
Added socket.io server to project.
Browse files Browse the repository at this point in the history
  • Loading branch information
trishantpahwa committed Nov 30, 2023
1 parent 45a3034 commit be87677
Show file tree
Hide file tree
Showing 5 changed files with 3,252 additions and 0 deletions.
2 changes: 2 additions & 0 deletions server/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
*.env
51 changes: 51 additions & 0 deletions server/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const dotenv = require("dotenv");
const express = require("express");
const http = require("http");
const { Server } = require("socket.io");

dotenv.config();
const app = express();
const server = http.createServer(app);
const io = new Server(server);

io.on("connection", (socket) => {

// Join a room.
socket.on("joinRoom", async (room) => {
try {
await socket.join(room);
} catch (error) {
console.error(`Error joining room: ${error}`);
}
});

// Broadcast the received message.
socket.on("message", async ({ room, message }) => {
try {
await socket.to(room).emit("message", message);
} catch (error) {
console.error(`Error broadcasting message: ${error}`);
}
});

socket.on("drawing-update", async ({ room, drawing }) => {
try {
await socket.to(room).emit("drawing-update", drawing);
} catch (error) {
console.error(`Error broadcasting drawing: ${error}`);
}
});

socket.on("disconnect", () => {
// console.log("user disconnected");
});
});

process.env.NODE_ENV !== "TEST"
? server.listen(process.env.PORT, () => {
console.log(`Listening on ${process.env.PORT}`);
})
: null;

module.exports = { server };

Loading

0 comments on commit be87677

Please sign in to comment.