与socket.io进行私密聊天

时间:2016-11-29 06:51:23

标签: node.js 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 = [],
	connections = [];
var onlineClients = {};




// Register events on socket connection
io.on('connection', function(socket){ 
	connections.push(socket);
	// console.log("connected socket", connections);

	socket.on("disconnect", function() {
		users.splice(users.indexOf(socket.username), 1);
		updateUsernames();
		connections.splice(connections.indexOf(socket), 1);
		console.log("disconnected socket", connections.length)
	});

	socket.on("send message", function(data) {
		// console.log(data);
		io.emit("new message", {msg: data, user: socket.username});
	});


	socket.on("notify user", function(data) {
		io.emit("notify user", {user: socket.username})
	});


	socket.on("new user", function(data) {
		socket.username = data;
		users.push(socket.username);
		updateUsernames();

	});

	function updateUsernames() {
		io.emit("get users", users);
	};

	socket.on("private", function(data, recipientName) {
		var recipient = connections.filter(function (recipient) {
			return recipient.username === recipientName;
		})[0];
			console.log(recipient.id);
			console.log(data);
		io.sockets.socket(recipient.id).emit("received private msg", data);

	});


	// socket.on("create room", function(room) {
	// 	socket.join(room);
	// 	io.sockets.in(room).emit('event', "hey wusup am in this room");
	// 	console.log(socket);

	// })

});

http.listen(PORT, function(){
  console.log('Server started on port ' + PORT);
});

2 个答案:

答案 0 :(得分:5)

  • 首先在聊天室中添加用户,以便在私人聊天室中轻松找到用户
  • 您加入私人房间的客户端代码

    <input type="text" class="form-control" id="user_email" placeholder="user_email" /> <button text="join room" class="btn btn-primary btn-block" onclick="a();"> Join Room</button>

  • 您在客户端的JavaScript代码

    function a(){ io.emit('privatechatrrom', {email:document.getElementById('user_email').value}); }

  • 您的服务器端代码,以便在您的房间中添加用户

    socket.on('privatechatroom',function(data){ socket.join(data.email); io.emit('res',{mes:"you are added"}) });

现在,您可以向最近添加到此会议室的人发送私人消息 客户端

function b()
{
  io.emit('sendmail',{email:document.getElementById('sender_mail').value,message:document.getElementById('message').value});
  $('#message').val('');
}


/*serverside code*/socket.on('sendmail',function(data)
{
    io.sockets.in(data.email).emit('new_msg', {msg: data.message});
            console.log(data.email);
});

答案 1 :(得分:0)

以下是我的问题的明确解决方案......

Send a message to Particular client(Private chat)

我希望它适合你起诉..