2012-05-17 25 views
11

El envío de mensajes a todos los clientes funciona bien, pero deseo enviar un mensaje a un nombre de usuario particular. mi archivo server.js parece. Lo que hace es cuando se ejecuta http://localhost:8080, el código de cliente agrega usuario a los nombres de usuario del objeto, así como en el objeto socket. Y devuelve instantáneamente el mensaje individual a cada uno de los clientes conectados.socket.io y node.js para enviar un mensaje a un cliente particular

//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'); 
    }); 
}); 

La parte que emite el mensaje

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

Respuesta

10

Prueba esto:

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 es salvado por socket.io y contiene identificador único de su cliente. Puede comprobar que el uso de este:

console.log(socket.id); 
+0

TypeError: io.sockets.socket no es una función –

+0

En 1.0 debe usar io.sockets.connected [socketid] .emit(); – milanchandna

1

usted tiene que almacenar todos los ID de cliente y de acuerdo con que tiene que conseguir Identificación del cliente particular y, utilizar siguiente código

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

entonces esto emitir en un cliente particular

Cuestiones relacionadas