我在使用我的聊天應用程序時遇到問題,我需要能夠向特定用戶發送私人消息,我可以選擇特定的用戶,但由於某種原因無法找到了解如何發送私人消息。與socket.io的私人聊天
下面你會發現我的服務器代碼,請大家幫忙:
var express = require('express');
var app = express();
var PORT = process.env.PORT || 8000;
var http = require('http').Server(app); // this is a node server that uses express as the boiler plate
var io = require('socket.io')(http); // socket! pass our server as a parameter to it
// use express static to expose a folder
app.use(express.static(__dirname + '/public'));
var users = [],
\t connections = [];
var onlineClients = {};
// Register events on socket connection
io.on('connection', function(socket){
\t connections.push(socket);
\t // console.log("connected socket", connections);
\t socket.on("disconnect", function() {
\t \t users.splice(users.indexOf(socket.username), 1);
\t \t updateUsernames();
\t \t connections.splice(connections.indexOf(socket), 1);
\t \t console.log("disconnected socket", connections.length)
\t });
\t socket.on("send message", function(data) {
\t \t // console.log(data);
\t \t io.emit("new message", {msg: data, user: socket.username});
\t });
\t socket.on("notify user", function(data) {
\t \t io.emit("notify user", {user: socket.username})
\t });
\t socket.on("new user", function(data) {
\t \t socket.username = data;
\t \t users.push(socket.username);
\t \t updateUsernames();
\t });
\t function updateUsernames() {
\t \t io.emit("get users", users);
\t };
\t socket.on("private", function(data, recipientName) {
\t \t var recipient = connections.filter(function (recipient) {
\t \t \t return recipient.username === recipientName;
\t \t })[0];
\t \t \t console.log(recipient.id);
\t \t \t console.log(data);
\t \t io.sockets.socket(recipient.id).emit("received private msg", data);
\t });
\t // socket.on("create room", function(room) {
\t // \t socket.join(room);
\t // \t io.sockets.in(room).emit('event', "hey wusup am in this room");
\t // \t console.log(socket);
\t // })
});
http.listen(PORT, function(){
console.log('Server started on port ' + PORT);
});
做一個私人房間,然後將消息發送給該房間內的某個用戶 – Adiii
客戶端只向服務器發送消息。如果您希望客戶端向特定用戶發送消息,那麼您會向服務器發送消息,並告訴服務器您希望服務器將其提供給哪個用戶。 – jfriend00