Gửi tin nhắn đến tất cả khách hàng hoạt động tốt nhưng tôi muốn gửi tin nhắn đến tên người dùng cụ thể. tệp server.js của tôi trông giống như. Những gì nó làm là khi http://localhost:8080
được chạy, mã máy khách sẽ thêm người dùng vào tên người dùng đối tượng cũng như trong đối tượng socket. Và ngay lập tức trả về thông điệp cá nhân cho từng khách hàng được kết nối.socket.io và node.js để gửi tin nhắn đến máy khách cụ thể
//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');
});
});
Phần phát ra thông điệp
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
});
LoạiError: io.sockets.socket không phải là hàm –
Trong 1.0, bạn nên sử dụng io.sockets.connected [socketid] .emit(); – milanchandna