socket.io create dynamic room - node.js

I have been googling for 2 days on my problem to dynamically create rooms on socket.io using nodeJs. When I create a room to the server, I make it like this:
socket.on('follow_me', function (user_id) { //I use the user_id of the user to create room
socket.join(user_id);
console.log(server.sockets.manager.rooms);
});
If next, I want to send a message to all persons connected in the by using
socket.join(user_id);
when i use :
socket.on('message', function (data) {
socket.broadcast.to(data.room).emit('recieve',data.message); //emit to 'room' except this socket
});
The other users in this room do not receive the message; but if I use:
socket.join(user_id);`,when i use :
socket.on('message', function (data) {
socket.broadcast.emit('recieve',data.message);
});
all user receive the message. Why room do not work for me? I think the code is good!
Tank's

socket.on('message', function (data) {
/*considering data.room is the correct room name you want to send message to */
io.sockets.in(data.room).emit('recieve', data.message) //will send event to everybody in the room while
socket.broadcast.to(data.room).emit('recieve', data.message) //will broadcast to all sockets in the given room, except to the socket which called it
/* Also socket.broadcast.emit will send to every connected socket except to socket which called it */
});
I guess what you need is io.sockets.in

Related

socket emit to only one user

I´ve been searching for the anwser but most of them i cant quite connect with my code so im hoping to get some help.
I want to send a message for a specific user, like a chat beetween 2 people.
For example, if i choose John how can i only send a mensage to him? im having much trouble in this
app.js
io.on('connection', function (socket) {
socket.on('chat', function (data) {
console.log(data);
//Specific user
//socket.broadcast.to(socketid).emit('message', 'Hello');
});
});
I have a mongodb database so how can i specify the socketid having the user id of the select user?
The below code can be used to send message to a specific client.
Point to be noted , every client connected has a unique socket id.
Store that id in an array. You can call any user with that id.
var id=[];
io.on('connection', function (socket) {
socket.on('chat', function (data) {
console.log(data);
id.push(${socket.id});
});
});
//to send to specific user
io.to(socket#id).emit('hey!')
You must create an userbased array. Here, you can get a special socket:
var users = [];
io.on('connection', function (socket) {
users.put(socket);
socket.on('chat', function (data) {
console.log(data);
users[0].emit('chat', data);
});
});
You can use a array based or an object based (here you can store it with the username, but you must implement a procedure to set the username after connection is available) variable.

How do I get other users socket.id?

How do I get other user's socket.id?
Since socket.id is keep changing, whenever the browser refresh or disconnect then connect again.
For example this line of code will solve my problem
socket.broadcast.to(id).emit('my message', msg);
But the question is How do i get that id?
Let say Jack wants to send a message to Jonah
Jack would use the above code to send the message, but how to get Jonah's socket id?
Just for the record, I already implemented socket.io and passport library so that I could use session in socket.io , the library is call passport-socket.io. So to get the user id in socket.io would be
socket.request.user._id
What i did for this was to maintain a database model(i was using mongoose) containing userId and socketId of connected users. You could even do this with a global array. From client side on socket connect, emit an event along with userId
socket.on('connect', function() {
socket.emit('connected', userName); //userName is unique
})
On server side,
var Connect = require('mongoose').model('connect');; /* connect is mongoose model i used to store currently connected users info*/
socket.on('connected', function(user) { // add user data on connection
var c=new Connect({
socketId : socket.id,
client : user
})
c.save(function (err, data) {
if (err) console.log(err);
});
})
socket.on('disconnect', function() { //remove user data from model when a socket disconnects
Connect.findOne({socketId : socket.id}).remove().exec();
})
This way always have connected user info(currently used socketId) stored. Whenever you need to get a users current socketId fetch it as
Connect.findOne({client : userNameOfUserToFind}).exec(function(err,res) {
if(res!=null)
io.to(res.socketId).emit('my message', msg);
})
I used mongoose here but you could instead even use an array here and use filters to fetch socketId of a user from the array.
The documentation suggests that `socket.on(SOME_MESSAGE's callback is provided an id as the fist param.
http://socket.io/docs/rooms-and-namespaces/#default-room
javascript
io.on('connection', function(socket){
socket.on('say to someone', function(id, msg){
socket.broadcast.to(id).emit('my message', msg);
});
});

Using Socket.io, how do I detect when a new channel/room has been created?

From the server, I want to be able to detect when a client creates new a room or channel. The catch is that the rooms and channels are arbitrary so i don't know what they will be until the user joins/subscribes. Something like this:
Server:
io.on('created', function (room) {
console.log(room); //prints "party-channel-123"
});
Client:
socket.on('party-channel-123', function (data) {
console.log(data)
})
I also can't have any special client requirements such as sending a message when the channel is subscribed as such:
socket.on('party-channel-123', function (data) {
socket.emit('subscribed', 'party-channel-123');
})
Server:
io.sockets.on('connection', function(socket) {
socket.on('createRoom', function(roomName) {
socket.join(roomName);
});
});
Client
var socket = io.connect();
socket.emit('createRoom', 'roomName');
the io object has references to all currently created rooms and can be used as such:
io.sockets.in(room).emit('event', data);
Hope this helps.
PS. I know its emitting the 'createRoom' that you probably don't want but this is how socket.io is used, this is pretty much copy/paste out of the docs. There are tons of examples on the socket.io website and others.

Having trouble managing multiple sockets [duplicate]

I'm having trouble getting basic client to client (or really client->server->client) working with socket.io. Heres the code I have right now:
io.sockets.on('connection', function (socket) {
users.push(socket.sessionId);
for(userID in users) {
console.log(userID);
io.sockets.socket(userID).emit('message', { msg: 'New User Connected succesfully' });
}
socket.emit('message', { msg: 'Connected succesfully' });
socket.on('my other event', function (data) {
console.log(data);
});
});
From my understanding, that should send the new user message to every connected user (individually, since i want to do actual individual messages later). Instead, I only get the 'connected successfully' message at the end. I don't get any errors or other negative indicators from my server or client.
Any ideas of why io.sockets.socket(userID).emit() doesn't work or what to use in its place?
Socket.io has the concept of rooms where, once a socket has joined a room, it will receive all message sent to a room, so you don't need to track who's in the room, deal with disconnections, etc...
On connection, you'd use:
socket.join('room')
And to send a message to everyone in that room:
io.sockets.in('room').emit('event_name', data)
More info on the socket.io wiki: https://github.com/LearnBoost/socket.io/wiki/Rooms
Try
users.push(socket); // without .sessionId
for (var u in users) {
// users[u] is now the socket
console.log(users[u].id);
users[u].emit('message', { msg: 'New User Connected succesfully' });
}
You can now also use ...
io.to('room').emit('event_name', data);
as an alternative to io.sockets.in

can i give my own id to a connected socket in nodejs

am trying to implement a multiuser communication app. I want to identify a user's socket with his id, so can i set socket's id to user' id like
socket.id=user.userId;
This may help you
io.sockets.on('connection', function (socket) {
console.log("==== socket ===");
console.log(socket.id);
socket.broadcast.emit('updatedid', socket.id);
});
you can save socket id in client side. When you want 1-1 message (private chat) use updated socket id. Some thing like this :
io.sockets.socket(id).emit('private message', msg, mysocket.id)
You can do this, but use property that doesn't clash with Node.js or any other frameworks keys
socket.myappsuperuserid = user.userId;
Here
client side
var socket = io.connect();
socket.on('connect', function () {
console.log("client connection done.....");
socket.emit('setUserId','random value');
});
On server side
io.sockets.on('connection', function (socket) {
socket.on('setUserId',function(uId){
socket.userId = uId;
});
});
This may help...
In socket.io when a user connects, socket.io will generate a unique socket.id which basically is a random unique unguessable id. What i'd do is after i connect i call socket.join('userId'). basically here i assign a room to this socket with my userId. Then whenever i want to send something to this user, i'd do like this io.to(userId).emit('my message', 'hey there?').
Hope this help.

Resources