Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Sending message to all client works well but I want to send message to particular username. my server.js file looks like. What it does is when http://localhost:8080 is run, the client code adds user to the object usernames as well as in socket object. And instantly returns the individual message to each of the connected client.

//var io = require('socket.io').listen(8080);
var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')
var usernames={};  
 app.listen(8080);

// on server started we can load our client.html page
function handler ( req, res ) {
  fs.readFile( __dirname + '/client.html' ,
  function ( err, data ) {
    if ( err ) {
      console.log( err );
      res.writeHead(500);
      return res.end( 'Error loading client.html' );
    }
    res.writeHead( 200 );
    res.end( data );
  });
};
io.set('log level', 1); // reduce logging
io.sockets.on('connection', function (socket) {

 socket.on('adduser', function(username){
        // store the username in the socket session for this client
        socket.username = username;
        // add the client's username to the global list
        usernames[username] = username;
        // send client to room 1
        console.log(username+' has connected to the server');
        // echo to client they've connected
  });

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

  socket.on('disconnect', function(){
        // remove the username from global usernames list
        delete usernames[socket.username];

        // echo globally that this client has left
       console.log(socket.username + ' has disconnected');
    });
});

The portion that emits message

socket.on('pmessage', function (data) {
        // we tell the client to execute 'updatechat' with 2 parameters
        io.sockets.emit("pvt",socket.username,data+socket.username); // This works and sends message to all clients
        io.sockets.socket(socket.username).emit("pvt",socket.username,data+socket.username); // THIS DOESNOT
   });
like image 479
WatsMyName Avatar asked May 17 '12 03:05

WatsMyName


People also ask

How do we send the message from one socket to another socket in node JS?

send() Method. The socket. send() method is an inbuilt application programming interface of class Socket within dgram module which is used to send the message from one socket to another socket.

How do I send a message to a socket?

The send() function initiates transmission of a message from the specified socket to its peer. The send() function sends a message only when the socket is connected (including when the peer of the connectionless socket has been set via connect()). The length of the message to be sent is specified by the len argument.

How do you make a Socket.IO chat?

Creating the application We're using the prompt() method to request the username. With socket. emit() we're emitting (sending a message) to our server. The first parameter is the event name and the second parameter is the data we're sending, in this case, just the username.

How does Socket.IO connect to client and server?

listen(port); // Create a Socket.IO instance, passing it our server var socket = io. listen(server); // Add a connect listener socket. on('connection', function(client){ console. log('Connection to client established'); // Success!


2 Answers

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);
like image 79
milanchandna Avatar answered Sep 21 '22 13:09

milanchandna


You have to store all client ids and according to that you have to get id of particular client and then you use following code

var store={};//this will store all client id and username e.g. store={jay:"34jhjshdj343sasa"}
socket.on('pmessage', function (data) {
    var receiverUserName=data.username;
    var message=data.message;
    var id = store[receiverUserName];//get ID
    // we tell the client to execute 'updatechat' with 2 parameters
    io.sockets.emit("pvt",socket.username,data+socket.username);
    io.sockets.socket(id).emit("pvt",socket.username,data+socket.username); 
});

Then this will emit on particular client

like image 31
Jayant Patil Avatar answered Sep 20 '22 13:09

Jayant Patil