0

in this below simple code i want to try after get connected user on nodeJs i can be reply any message after send pm from android device, in this code how to send message for connected user by socket?

var io  = require('socket.io');  
var server = io.listen(4732);

var android_socket   = undefined;

server.sockets.on('connection', function(socket) {  
    socket.on('user', function(data) {

        if (data.type == "client")
            //saving socket
            android_socket = socket;
        }

    });

    socket.on("pm", function(data) {
        /* Reply message to android_socket */          
    });
});

console.log('server is connected...');
DolDurma
  • 15,753
  • 51
  • 198
  • 377

1 Answers1

2

You can simply emit an event to the same socket that received the pm event:

socket.on("pm", function(data) {
    /* send reply event */
    socket.emit('foo', {data: 123});
});

That socket is attached to an android client.

There is no need to store any android_socket references. In fact, your approach (which stores a single socket reference) would not have worked properly anyway, since there could be multiple android socket connections open at the same time.

cybersam
  • 63,203
  • 6
  • 53
  • 76
  • so if this is true to dont necessery save socket, how to find socket id between some connected socket into server – DolDurma Feb 24 '15 at 14:47
  • You may be asking a duplicate of this question: http://stackoverflow.com/questions/8467784/sending-a-message-to-a-client-via-its-socket-id. In its very nice accepted answer, the `clients` and `users` hashes store info about the sockets and users for later use. – cybersam Feb 24 '15 at 17:46