I am using nodejs and socketio. I made a private chat app which sends message to selected user.
My current code is :
chat_room.sockets.socket(user).emit(
'chat',
{
message : message,
from : sockets[socket.id].username
}
);
Now I created rooms and I want to send message to a user of a specific room.
I tried below code but not working
socket.get('room', function(err, room) {
chat_room.sockets.socket(room)(user).emit(
'chat',
{
message : message,
from : sockets[socket.id].username
}
);
});
Its wrong and it gave me an error :
C:\Users\Niraj\Desktop\node\joomla-chat\app.js:62
chat_room.sockets.socket(room)(user).emit(
^ TypeError: object is not a function
at chat_room.sockets.on.socket.on.socketID (C:\Users\Niraj\Desktop\node\joomla-chat\app.js:62:45)
at Client.get (C:\Users\Niraj\Desktop\node\joomla-chat\node_modules\socket.io\lib\stores\memory.js:86:3)
at Socket.get (C:\Users\Niraj\Desktop\node\joomla-chat\node_modules\socket.io\lib\socket.js:258:14)
at Socket.chat_room.sockets.on.socket.on.socketID (C:\Users\Niraj\Desktop\node\joomla-chat\app.js:48:16)
at Socket.EventEmitter.emit [as $emit] (events.js:96:17)
at SocketNamespace.handlePacket (C:\Users\Niraj\Desktop\node\joomla-chat\node_modules\socket.io\lib\namespace.js:335:22)
at Manager.onClientMessage (C:\Users\Niraj\Desktop\node\joomla-chat\node_modules\socket.io\lib\manager.js:487:38)
at WebSocket.Transport.onMessage (C:\Users\Niraj\Desktop\node\joomla-chat\node_modules\socket.io\lib\transport.js:387:20)
at Parser. (C:\Users\Niraj\Desktop\node\joomla-chat\node_modules\socket.io\lib\transports\websocket\hybi-16.js:39:10)
at Parser.EventEmitter.emit (events.js:96:17)
How can I send message to a specific user of a room
——————————-EDIT—————————-
So if I do :
socket.get('room', function(err, room) {
chat_room.sockets.socket(user).emit(
'chat',
{
message : message,
from : sockets[socket.id].username
}
);
});
Then this will fire the message to Mr.X to ABC room
Am I right?
Regardless of whether or not the user you want to contact is in a room, the easiest way to contact them, provided you have the proper identifying information, is still just a simple socket.emit().
You stated that you already have their socket.id; if so, then getting their socket object is as simple as:
io.sockets.sockets[socket.id].To send a message you can then say:
io.sockets.sockets[socket.id].emit('identifier', data);That should answer your question, although these are two additional things you may find helpful:
-To broadcast to the entire room you are focusing on:
io.sockets.in('room').emit('event_name', data)-There is a very rich amount of information regarding both rooms and connected sockets stored within io.sockets. I strongly recommend that you put a
console.log(io.sockets);in the beginning of your code and inspect the object closely to see what else you can access.Hope this helps!