本文介绍了socket.io和node.js将消息发送到特定客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
向所有客户端发送消息效果很好,但是我想向特定的用户名发送消息.我的server.js文件看起来像.它的作用是在运行http://localhost:8080
时,客户端代码将用户添加到对象用户名以及套接字对象中.并立即将单个消息返回给每个连接的客户端.
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');
});
});
发出消息的部分
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
});
推荐答案
尝试一下:
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由socket.io保存,并且包含客户端的唯一ID.您可以使用以下方法进行检查:
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);
这篇关于socket.io和node.js将消息发送到特定客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!