Skip to content

Instantly share code, notes, and snippets.

@gibrandev
Created November 9, 2022 09:29
Show Gist options
  • Save gibrandev/e129a2f69e8ba2d9d093c350b37e5f79 to your computer and use it in GitHub Desktop.
Save gibrandev/e129a2f69e8ba2d9d093c350b37e5f79 to your computer and use it in GitHub Desktop.
Socket io dynamic rooms
const express = require("express");
const { createServer } = require("http");
const { Server } = require("socket.io");
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
cors: {
origin: "*",
methods: "*",
credentials: true
},
allowEIO3: true
});
app.get('/', (req, res) => {
res.send('Hello World!')
})
io.on("connection", (socket) => {
var chatId = socket.handshake.query.chatId;
socket.join(chatId);
socket.on("message", (msg) => {
socket.to(chatId).emit("message", msg);
});
socket.on("disconnect", (reason) => {
console.log(reason);
});
socket.on("leave", () => {
socket.leave(chatId);
socket.disconnect();
});
});
httpServer.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment