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.
Related
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.
I want my client-side code to send the server the user's userid when establishing the connection, then i want the server to check the database for new messages for each user that is connecting, and send the user the number of new messages it has when new messages are available.
My client-side code:
var socket = io.connect('http://localhost:8000');
socket.on('connect', function () {
socket.emit('userid', '1');
});
socket.on('new_message', function (data) {
var number_of_messages= "<p>"+data.number+"</p>";
$('#container').html(number_of_messages);
});
My server-side code:
io.sockets.on( 'userid', function (data) {
console.log('userid: '+data);
});
My problem is that the above code is not working: the userid is never received by the serverside and the on('userid') is never called.
My question is how to know which socket sent this user id and how to send to only this specific socket a certain message.
I have solved the problem by saving the clients socket and their id into a global array. this is not a good solution but it works; I know there are rooms and namespaces but I never used it..
socket.io namespaces and rooms
however,
(I used express)
client:
var socket = io.connect('http://localhost:3000',{reconnection:false});
socket.once('connect', function() {
socket.emit('join', '#{id}');
};
server:
var clients = [];
app.io.on('connection', function(socket) {
socket.on('join', function(data) {
clients.push({
ws: socket,
id: data
});
//retrive the messages from db and loop the clients array
//and socket.send(things)
}
}
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);
});
});
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.
What is the proper way to manage multiple chat rooms with socket.io?
So on the server there would be something like:
io.sockets.on('connection', function (socket) {
socket.on('message', function (data) {
socket.broadcast.emit('receive', data);
});
});
Now this would work fine for one room, as it broadcasts the message out to all who are connected. How do you send messages to people who are in specific chat rooms though?
Add .of('/chat/room_name')?
Or store an array of everybody in a room?
Socket.IO v0.7 now gives you one Socket per namespace you define:
var room1 = io.connect('/room1');
room1.on('message', function () {
// chat socket messages
});
room1.on('disconnect', function () {
// chat disconnect event
});
var room2 = io.connect('/room2');
room2.on('message', function () {
// chat socket messages
});
room2.on('disconnect', function () {
// chat disconnect event
});
With different sockets, you can selectively send to the specific namespace you would like.
Socket.IO v0.7 also has concept of "room"
io.sockets.on('connection', function (socket) {
socket.join('a room');
socket.broadcast.to('a room').send('im here');
io.sockets.in('some other room').emit('hi');
});
Source: http://socket.io/#announcement
Update: Both Now.js and Bridge are now dead, see now.js dead and bridge dead. Socket.io seems to have adopted the callback feature as of v0.9, which is a good step forward.
While it isn't directly Socket.io related, Now.js (a higher level abstraction ontop of Socket.io) supports groups - http://nowjs.com/doc
They have a multi-room-chat example in their offocial repo here: https://github.com/Flotype/now/blob/master/examples/multiroomchat_example/multiroomchat_server.js