Sending message to specific client in Socket IO - node.js

I'm using Socket IO v1.4.5 and have tried 3 different ways below but dont have any result.
client.emit('test', 'hahahaha');
io.sockets.socket(id).emit('test',''hahaha);
io.sockets.connected[id].emit('test','hahaha');
Here is my server side
var socket = require( 'socket.io' );
var express = require( 'express' );
var http = require( 'http' );
var dateFormat = require('date-format');
var app = express();
var server = http.createServer( app );
var io = socket.listen( server );
io.sockets.on( 'connection', function( client ) {
user[client.id]=client;
//when we receive message
client.on('message', function( data ) {
console.log( 'Message received from' + data.name + ":" + data.message +' avatar' +data.avatar );
client.emit('test', 'hahahaha');
});
Any help would be great.Thanks for help.Kind Regard

To send a message to a specific client you need to do it like so:
socket.broadcast.to(socketid).emit('message', 'for your eyes only');
Here is a nice little cheat sheet for sockets:
// sending to sender-client only
socket.emit('message', "this is a test");
// sending to all clients, include sender
io.emit('message', "this is a test");
// sending to all clients except sender
socket.broadcast.emit('message', "this is a test");
// sending to all clients in 'game' room(channel) except sender
socket.broadcast.to('game').emit('message', 'nice game');
// sending to all clients in 'game' room(channel), include sender
io.in('game').emit('message', 'cool game');
// sending to sender client, only if they are in 'game' room(channel)
socket.to('game').emit('message', 'enjoy the game');
// sending to all clients in namespace 'myNamespace', include sender
io.of('myNamespace').emit('message', 'gg');
// sending to individual socketid
socket.broadcast.to(socketid).emit('message', 'for your eyes only');
Credit to https://stackoverflow.com/a/10099325
The easiest way rather than sending directly to the socket, would be creating a room for the 2 users to use and just send messages freely in there.
socket.join('some-unique-room-name'); // Do this for both users you want to chat with each other
socket.broadcast.to('the-unique-room-name').emit('message', 'blah'); // Send a message to the chat room.
Otherwise, you're going to need to keep track of each individual clients socket connection, and when you want to chat you'll have to look up that sockets connection and emit specifically to that one using the function I said above. Rooms are probably easier.

Socket.io Version 2.0.3+
Sending a message to a specific socket
let namespace = null;
let ns = _io.of(namespace || "/");
let socket = ns.connected[socketId] // assuming you have id of the socket
if (socket) {
console.log("Socket Connected, sent through socket");
socket.emit("chatMessage", data);
} else {
console.log("Socket not connected, sending through push notification");
}

Simply do this
io.socket.in('room').emit("send message to everyone", data);

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

How to configure socket io and socket io client

Good day
I need to connect a lot of pc's to a main server, through a server of units
I have something but I don't have all complete
Main Server
socketIo = require("socket.io"),
ioServer = socketIo(server),
ioServer.sockets.on("connection",function(socket){
// Display a connected message
console.log("Server-Client Connected!");
// When we receive a message...
socket.on("message",function(data){
// We got a message... I dunno what we should do with this...
console.log(data);
console.log(data.from + " is connected with ip " + data.ip);
socket.emit('message', { 'from': '10.19.17.101', 'answer':'I already added you '+data.from });
});
});
Server Units
socketIo = require("socket.io"),
ioServer = socketIo(server),
ioClient = require("socket.io-client")('http://10.19.17.101:7700')
ioClient.on('connect', function(){
ioClient.on('message',function(data){
console.log(data.from + " answered: " + data.answer);
ioServer.to('pxe4').emit('message',data);
});
ioClient.emit('message',{ 'from': 'pxe4', 'ip':'10.19.16.84' });
});
ioServer.sockets.on("connection",function(socket){
// Display a connected message
console.log("User-Client Connected!");
// When we receive a message...
socket.on("message",function(data){
// We got a message... I dunno what we should do with this...
console.log(data);
console.log(data.from + " is connected with ip " + data.ip);
socket.emit('message', { 'from': '10.19.16.84', 'answer':'I already added you '+data.from });
ioClient.emit("message",data);
});
socket.on("disconnect",function(data){
// We need to notify Server 2 that the client has disconnected
ioClient.emit("message","UD,"+socket.id);
// Other logic you may or may not want
// Your other disconnect code here
});
});
Units
ioClient = require("socket.io-client")('http://10.19.16.84:7770'),
ioClient.on('connect', function(){
ioClient.on('message',function(data){
// We received a message from Server 2
// We are going to forward/broadcast that message to the "Lobby" room
console.log(data.from + " answered: " + data.answer);
});
ioClient.emit('message',forsend);
});
I was wondering if at this moment I can send some information from Main Server to a specific unit?
If someone could help me, I will be thankful.
When connecting from each client on the main server or Server Units you recive a socket object which contains socketid. You have to save those socket id's in some data storge for speedy access with the server information. When you have to emit data to specific socket you have to query that specific socket from data storage and emit the data. On disconnect you have to pull that particular socket from data storage

use node.js cluster with socket.io chat application

I'm trying to learn node.js cluster with socket.io to create a chat application... the problem is that I can't seem to get things working.
i've been trying to go through all the tutorials including the one that I get from this http://stackoverflow.com/questions/18310635/scaling-socket-io-to-multiple-node-js-processes-using-cluster/18650183#18650183
when I try to open two browsers, the messages does not go to the other browser.
here's the code that i got
var express = require('express'),
cluster = require('cluster'),
net = require('net'),
socketio = require('socket.io'),
socket_redis = require('socket.io-redis');
var port = 3000,
num_processes = require('os').cpus().length;
if (cluster.isMaster) {
// This stores our workers. We need to keep them to be able to reference
// them based on source IP address. It's also useful for auto-restart,
// for example.
var workers = [];
// Helper function for spawning worker at index 'i'.
var spawn = function(i) {
workers[i] = cluster.fork();
// Optional: Restart worker on exit
workers[i].on('exit', function(code, signal) {
console.log('respawning worker', i);
spawn(i);
});
};
// Spawn workers.
for (var i = 0; i < num_processes; i++) {
spawn(i);
}
// Helper function for getting a worker index based on IP address.
// This is a hot path so it should be really fast. The way it works
// is by converting the IP address to a number by removing non numeric
// characters, then compressing it to the number of slots we have.
//
// Compared against "real" hashing (from the sticky-session code) and
// "real" IP number conversion, this function is on par in terms of
// worker index distribution only much faster.
var worker_index = function(ip, len) {
var s = '';
for (var i = 0, _len = ip.length; i < _len; i++) {
if (!isNaN(ip[i])) {
s += ip[i];
}
}
return Number(s) % len;
};
// Create the outside facing server listening on our port.
var server = net.createServer({ pauseOnConnect: true }, function(connection) {
// We received a connection and need to pass it to the appropriate
// worker. Get the worker for this connection's source IP and pass
// it the connection.
var worker = workers[worker_index(connection.remoteAddress, num_processes)];
worker.send('sticky-session:connection', connection);
}).listen(port);
} else {
// Note we don't use a port here because the master listens on it for us.
var app = new express();
// Here you might use middleware, attach routes, etc.
app.use('/assets', express.static(__dirname +'/public'));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
// Don't expose our internal server to the outside.
var server = app.listen(),
io = socketio(server);
// Tell Socket.IO to use the redis adapter. By default, the redis
// server is assumed to be on localhost:6379. You don't have to
// specify them explicitly unless you want to change them.
io.adapter(socket_redis({ host: 'localhost', port: 6379 }));
// Here you might use Socket.IO middleware for authorization etc.
io.on('connection', function(socket) {
console.log('New client connection detected on process ' + process.pid);
socket.emit('welcome', {message: 'Welcome to BlueFrog Chat Room'});
socket.on('new.message', function(message) {
socket.emit('new.message', message);
})
});
// Listen to messages sent from the master. Ignore everything else.
process.on('message', function(message, connection) {
if (message !== 'sticky-session:connection') {
return;
}
// Emulate a connection event on the server by emitting the
// event with the connection the master sent us.
server.emit('connection', connection);
connection.resume();
});
}
If I understand correctly, your problem is that the messages from a client are not broadcasted to the other clients. you can solve this easily using :
io.on('connection', function(socket) {
console.log('New client connection detected on process ' + process.pid);
socket.emit('welcome', {message: 'Welcome to BlueFrog Chat Room'});
socket.on('new.message', function(message) {
socket.emit('new.message', message); // this line sends the message back to the emitter
socket.broadcast.emit('my message', msg); // this broadcasts the message to all the clients
})
});
There are different ways to emit a message. The one you're using emits the message only to the socket that first sent a 'new.message' message to the server. Which means that a socket will receive the message that you emit there only if it first sent a message 'new.message'. That's why, in your browser, the client originating the message is the only one receiving it back.
Change it to:
socket.on('new.message', function(message) {
io.sockets.emit('new.message', message);//use this if even the browser originating the message should be updated.
socket.broadcast.emit('new.message', message);//use this if everyone should be updated excpet the browser source of the message.
})
Here are the different ways you can emit:
io.sockets.on('connection', function(socket) {
//This message is only sent to the client corresponding to this socket.
socket.emit('private message', 'only you can see this');
//This message is sent to every single socket connected in this
//session, including this very socket.
io.sockets.emit('public message', 'everyone sees this');
//This message is sent to every single connected socket, except
//this very one (the one requesting the message to be broadcasted).
socket.broadcast.emit('exclude sender', 'one client wanted all of you to see this');
});
You can also add sockets to different rooms when they connect so that you only communicate messages with sockets from a given room:
io.sockets.on('connection', function(socket) {
//Add this socket to a room called 'room 1'.
socket.join('room 1');
//This message is received by every socket that has joined
//'room 1', including this one. (Note that a socket doesn't
//necessarily need to belong to a certain room to be able to
//request messages to be sent to that room).
io.to('room 1').emit('room message', 'everyone in room 1 sees this');
//This message is received by every socket that has joined
//'room 1', except this one.
socket.broadcast.to('room 1').emit('room message', 'everyone in room 1 sees this');
});

Send a message from client to server on connection node.js

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)
}
}

socket.io send packet to sender only

I have yet to figure out how to directly respond to only the sender using socket.io
I have learned that io.sockets.emit sends to all clients but I wont to send information back to the sender.
code:
socket.on('login', function (data) {
db.users.find({username: cc.lowerCase(data.username)}, function(err, users) {
if (users.length > 0) {
users.forEach( function(user) {
console.log(user.length);
if (user.password == data.password) {
io.sockets.emit('login', { username: user.username });
} else {
io.sockets.emit('error', { message: "Wrong username or password!" });
}
});
} else {
io.sockets.emit('error', { message: "Wrong username or password!" });
}
});
});
When your server listens, you usually get a socket at the "connection" event :
require('socket.io').on('connect', function(socket){
A socket connects 2 points : the client and the server. When you emit on this socket, you emit to this specific client.
Example :
var io = require('socket.io');
io.on('connect', function(socket){
socket.on('A', function(something){
// we just received a message
// let's respond to *that* client :
socket.emit('B', somethingElse);
});
});
Be careful that those are two different calls :
socket.emit : emit to just one socket
io.sockets.emit : emit to all sockets
Simple example
The syntax is confusing in socketio. Also, every socket is automatically connected to their own room with the id socket.id (this is how private chat works in socketio, they use rooms).
Send to the sender and noone else
socket.emit('hello', msg);
Send to everyone including the sender(if the sender is in the room) in the room "my room"
io.to('my room').emit('hello', msg);
Send to everyone except the sender(if the sender is in the room) in the room "my room"
socket.broadcast.to('my room').emit('hello', msg);
Send to everyone in every room, including the sender
io.emit('hello', msg); // short version
io.sockets.emit('hello', msg);
Send to specific socket only (private chat)
socket.broadcast.to(otherSocket.id).emit('hello', msg);
late but better than never ;)
I had smth like this:
io.on('connection', function(socket){
socket.emit('some event', data);
socket.on('private event', function(message){
this.emit('other private event', message);
}
}
After some testing, I realized that 'this.emit' inside 'private event' closure send back only to sender. So i tried 'this.broadcast.emit', which send the message to all connected except the sender. I believe this is what you want from your code.

Resources