Created
November 9, 2022 09:29
-
-
Save gibrandev/e129a2f69e8ba2d9d093c350b37e5f79 to your computer and use it in GitHub Desktop.
Socket io dynamic rooms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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