Reputation: 11
I would like to implement rooms for chatting in my node.js
project using socket.io
. I would like to create a room based on any forward slash link visited that all people who access that link are joined in that rooms.
For example:
If my website is nodeapp.com
, a room can be created by going to nodeapp.com/funroom
. Anyone who goes to nodeapp.com/funroom
(while there is at least 1 person in the room) can globally chat.
I do not need help implementing chat, just rooms.
Thanks a lot
Upvotes: 1
Views: 2739
Reputation: 651
I have written a similar app for my university, using the following setup:
A user browses to nodeapp.com/desiredRoom
. My express server has the following route:
app.get("/:roomName", function(res, req){
res.render("student", {room:req.params.roomName});
})
This renders a template (using Jade), with the input parameter room
defined by the URL. I then pass this parameter to the client as a javascript variable. The Jade template looks something like this:
html
head
script.
room="#{room}";
script(src='/clientScript.js');
body
...
On the client side, clientScript.js
now knows what room to join. You can use this system to perform more advanced room requests. For example, I split up the rooms based on multiple parameters in the URL.
Upvotes: 1
Reputation: 29167
1) You need send room name to server:
// Client
var socket = io('/');
socket.emit('joinroom', window.location.pathname);
socket.on("new user", function(data) {
console.log("New user. Total users: ", data);
});
2) You need get room name on server and join:
// Backend
var io = require('socket.io')();
var rooms = {};
io.on('connection', function(socket) {
socket.on('joinroom', function(room) {
this.join(room);
if (typeof rooms[room] ==== "undefined") rooms[room] = {};
rooms[room].count = rooms[room].total ? rooms[room].total+1 : 1;
io.to(room).emit("new user", rooms[room].count)
});
});
Upvotes: 2