Socketio client identify which room the message came from - node.js

If a client joined multiple rooms and receives messages in those rooms is there a way for the client to identify which room his message came from (without incorporating the room in the message)?

When you make a socket join a particular room, you can set property of that socket to that room like this:
io.sockets.on('connection', function (socket) {
var room = "yourRoomName";
socket.on('join room', function(data){
socket.join(room);
socket.room = room;
});
socket.on('message', function(data){
console.log('Received message '+data.message+' from room '+socket.room);
})
});
Client:
socket.emit('join room', {your: 'data'});
socket.emit('message', {message: 'your message'});

Related

how to send typing alert and message to users in a particular room using nodejs socket.io

The code below works fine by broadcasting typing notification and chat messages to all connected users.
Here is what I want: How do I send typing notification and chat messages only to users connected to a particular room
say Room1, Room2 etc.
here is the code
index.html
var socket = io();
var user = 'nancy';
function submitfunction(){
var from = 'nancy';
var message = 'hello Nancy';
socket.emit('chatMessage', from, message);
}
function notifyTyping() {
var user = 'nancy'
socket.emit('notifyUser', user);
}
socket.on('chatMessage', function(from, msg){
//sent message goes here
});
socket.on('notifyUser', function(user){
$('#notifyUser').text(nancy is typing ...');
setTimeout(function(){ $('#notifyUser').text(''); }, 10000);
});
server.js
var io = require('socket.io')(http);
io.on('connection', function(socket){
socket.on('chatMessage', function(from, msg){
io.emit('chatMessage', from, msg);
});
socket.on('notifyUser', function(user){
io.emit('notifyUser', user);
});
});
am using npm installed socket.io ^2.3.0
To send the message to a specific room, you will have to create and join a room with roomId. Below is a basic code snippet
//client side
const socket = io.connect();
socket.emit('create', 'room1');
// server side code
socket.on('create', function(room1) {
socket.join(room1);
});
To emit data to a specific room
// sending to all clients in 'room1'except sender
socket.to('room1').emit('event',data);
// sending to all clients in 'room1' room, including sender
io.in('room1').emit('event', 'data');
You can follow this question for details on how to create a room?
Creating Rooms in Socket.io
This emit cheat sheet might also be useful:
https://github.com/socketio/socket.io/blob/master/docs/emit.md

Regarding the rooms creation in socket.io

I want to create a room in which rooms should be case insensitive means if room a and room A should open same room or room LOT and room LOt should also same room. So what should i do to make such changes in the room.
Convert all characters of your room name to lowercase (or uppercase) before you connect and before you send messages.
Server side:
io.on('connection', function(socket){
// Join the room
socket.on('join', function(room){
socket.join(room.toLowerCase());
}
// Send message to room
socket.on('message', function(data){
socket.broadcast.to(data.room.toLowerCase()).emit('message', data.message);
}
});
Client side:
socket.emit('join', 'RoOmNaMe');
socket.emit('message', { room: 'rOoMnAmE', message: 'Some message...'});

Why does socket.io not join a given room?

I'm having problems when I try to join a socket to a room. The name of the room is the socket.id and it is assigned when it is connected. But when this happens it doesn't join to room. What could be the error?
Client code:
var socket = io();
socket.on("connect", function() {
socket.emit("joinRoom", socket.id);
});
socket.on("agentMessage", function(msg) {
$('#messages').append("<div class='agent-messages'><p>" + msg + "</p></div>");
});
Server code:
io.on("connection", (socket) => {
let roomID;
socket.on("joinRoom", (socket_id) => {
roomID = socket_id;
socket.join(roomID);
socket.to(roomID).emit("agentMessage", "Welcome!");
});
socket.on("disconnect", () => {
socket.leave(socket_id);
});
});
Your client is actually joining the room, but it is not sending the message. As you are sending message from the server side you cannot send it using the socket, as socket represents a client connection and cannot throw events on behalf of server. You have to use
io.to(roomID).emit("agentMessage", "Welcome!");
as io represents a server instance and can throw events on behalf of server(actually it is the server).
Reference

Unable to log socket id during disconnection in Node.js

I am trying to log the socket id when a user logs out of a chat room.
Currently the logger is saying 'transport close has left the chatroom' instead of logging the socket id.
I have been able to get it to log 'transport close' or 'undefined' but can't seem to get it to save the socket.id before the connection closes. What am I doing wrong?
io.on('connection', function(socket){
var user_id = socket.id;
io.emit('broadcast', `--${user_id} has joined the chat room`);
console.log(`[${user_id}] has joined the chat room`);
socket.on('chat message', function(msg){
io.emit('chat message', `[${user_id}] ${msg}`);
console.log(`[${user_id}] ${msg}`);
});
socket.on('disconnect', function(user_id){
io.emit('broadcast', `${user_id} has left the chat room`);
console.log(`${user_id} has left the chat room`);
})
});
Use socket.id instead of user_id. Your callback function(user_id) is incorrect.
socket.on('disconnect', function(){
io.emit('broadcast', socket.id + ' has left the chat room');
console.log(socket.id + ' has left the chat room');
})

socket.io not sending to room using socket.to('myroom').emit

I am using socket.io 1.4.0.
I am trying to send a message to put the client in a room called 'myroom', then send a message to the room from the client and then get the response from the room. However I get no response from using
socket.to('myroom').emit('message', 'what is going on, party people?');
Here is my client code:
socket.on('connect', function() {
// Connected, join the booking room for to receive messages for this room
socket.emit('room', 'myroom');
});
socket.on('message', function(msg){
console.log('message: ' + msg);
});
socket.emit('booking room message', {roomid: 'myroom', message: 'hello'});
Here is my server code:
// Set up the Socket.IO server
var io = require("socket.io")(server)
.use(function(socket, next) {
// Wrap the express middleware
sessionMiddleware(socket.request, {}, next);
})
.on("connection", function(socket) {
console.log(socket.request.session);
if (socket.request.session.passport) {
var userId = socket.request.session.passport.user;
//Sign up client for the room from client side.
socket.on('room', function(room) {
socket.join(room);
console.log(userId + ' has joined booking room: ' + room);
});
//make a room for this user
socket.join(userId);
console.log("User ID: " + userId + " connected. socketID: " + socket.id);
socket.on('disconnect', function() {
console.log("User ID: " + userId + " disconnected.");
});
socket.on('booking room message', function(data) {
console.log('message sent from browser to a room');
console.log(data);
socket.to('myroom').emit('message', 'what is going on, party people?');
});
}
});
I get a message back from the server as expected when I use :
socket.emit('message', 'what is going on, party people?');
So there is something wierd going on with the join room function. A couple of things to note, I have some middleware tha gets the ID from express - dont think that is having any impact. Also I create a seperate room for the userID.
Can a user be in two rooms at once? I am not sure what is causing this.
Thanks,
it seemed that neither to or in will send the response back to the same client. The code above did send to other clients in the room however.

Resources