gpt4 book ai didi

node.js - socket.io 和 node.js 向特定客户端发送消息

转载 作者:IT老高 更新时间:2023-10-28 23:16:31 26 4
gpt4 key购买 nike

向所有客户端发送消息效果很好,但我想向特定用户名发送消息。我的 server.js 文件看起来像。它的作用是当 http://localhost:8080 运行时,客户端代码将用户添加到对象用户名以及套接字对象中。并立即将单个消息返回给每个连接的客户端。

//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。您可以使用以下方法进行检查:

console.log(socket.id);

关于node.js - socket.io 和 node.js 向特定客户端发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10629497/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com