Send Message to Specific Client with Socket.Io and Node.Js

Send message to specific client with socket.io and node.js

Well you have to grab the client for that (surprise), you can either go the simple way:

var io = io.listen(server);
io.clients[sessionID].send()

Which may break, I doubt it, but it's always a possibility that io.clients might get changed, so use the above with caution

Or you keep track of the clients yourself, therefore you add them to your own clients object in the connection listener and remove them in the disconnect listener.

I would use the latter one, since depending on your application you might want to have more state on the clients anyway, so something like clients[id] = {conn: clientConnect, data: {...}} might do the job.

How do i make socket.io send emit message to only one client?

I guess one of the comments directs you to a few potential answers. But just in case a struggling coder has the same issue, here is what i did that resolved it.

server.js

io.on('connection', function(socket) {
io.to(socket.id).emit('private', `your secret code is ${code}`);
});

client.js

socket.on('private', function(msg) {
alert(msg);
});

https://socket.io/docs/emit-cheatsheet/ has a bunch of useful information in a small amount of room. also heres the link th the other question in case you want to know more then one solution:

Send message to specific client with socket.io and node.js

How to send a message to a particular client with socket.io

When a user connects, it should send a message to the server with a username which has to be unique, like an email.

A pair of username and socket should be stored in an object like this:

var users = {
'userA@example.com': [socket object],
'userB@example.com': [socket object],
'userC@example.com': [socket object]
}

On the client, emit an object to the server with the following data:

{
to:[the other receiver's username as a string],
from:[the person who sent the message as string],
message:[the message to be sent as string]
}

On the server, listen for messages. When a message is received, emit the data to the receiver.

users[data.to].emit('receivedMessage', data)

On the client, listen for emits from the server called 'receivedMessage', and by reading the data you can handle who it came from and the message that was sent.

send message to one user using Socket.io

Indeed you need to store the incoming connection.

Client:

var userid = '69b6';//anything you like
var con = io.connect('localhost:4545/', { query: `userid=${userid}` });

Server:

var users = {} ;
io.on('connection', function(client){
users[client.handshake.query.userid] = client;
});

//you want to send something to a user
users[userid].emit('yolo', data);

EDIT: I reworked your code a bit

var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
var users = {};

server.listen(3000);

var redisClient = redis.createClient();

io.on('connection', function (socket) {
var userId = socket.handshake.query.userid;
users[userId] = socket;
});

redisClient.subscribe('message');
redisClient.on("message", function(channel, message) {
var message = JSON.parse(message);
var userId = message.id;
var userSocket = users[userId] || null;

console.log('=======[Message received]=======');
console.log('UserId:', userId);
console.log('SocketId:', userSocket.id);

if(userSocket){
userSocket.emit(channel, message.msg);
console.log("Message was succefully sent!");
}else{
console.log('User socket unavailable');
}
});

Tell me if it works and if you have difficulties understanding what I changed.

send message to specific client using soocket.io while socket id changes rapidly

Making my comment into an answer since it was indeed the issue:

The problem to fix is the rapidly disconnecting/reconnecting clients. That is a clear sign that something in the configuration is not correct.

It could be that network infrastructure is not properly configured to allow long lasting socket.io/webSocket connections. Or, if your system is clustered, it could be caused by non-sticky load balancing.

So, each time the connection is shut-down by the network infrastructure, the client-side socket.io library tries to reconnect creating a new ID for the new connection.

socket.io and node.js to send message to particular client

Try this:

socket.on('pmessage', function (data) {
// we tell the client to execute 'updatechat' with 2 parameters
io.sockets.emit("pvt",socket.username,data+socket.username);
io.sockets.socket(socket.id).emit("pvt",socket.username,data+socket.username);
});

socket.id is saved by socket.io and it contains unique id of your client.
You can check that using this:

console.log(socket.id);


Related Topics



Leave a reply



Submit