本文介绍了Socket io私人消息传递问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
//Client JS File
var socket = io.connect(),
userEnterDiv = document.getElementById('userEnterDiv'),
userNameErrorMsg = document.getElementById('userNameErrorMsg'),
userNameInput = document.getElementById('userNameInput'),
enterBtn = document.getElementById('enterBtn'),
mainDiv = document.getElementById('mainDiv'),
usersDivContainer = document.getElementById('usersDivContainer'),
displayUsers = document.getElementById('displayUsers'),
chatDivContainer = document.getElementById("chatDivContainer"),
chatOutput = document.getElementById('chatOutput'),
typingOutput = document.getElementById('typingOutput'),
msg = document.getElementById('messageTextArea'),
chatBtn = document.getElementById('chatButton');
//Enter to Chat
enterBtn.addEventListener('click', function(e){
e.preventDefault();
socket.emit('new user', userNameInput.value, function(data){
if(data) {
userEnterDiv.style.display = "none";
mainDiv.style.display = "block";
} else {
userNameErrorMsg.innerHTML = 'Error: try again';
}
});
});
//display usernames on chat inside div displayUsers
// socket.on('usernames', function(data){
// displayUsers.innerHTML = '';
// for(var i=0; i<data.length; i++){
// displayUsers.innerHTML += `${`<div id="nameOnDisplay-${data[i]}">${data[i]}</div>`}`; // '<div id="nameOnDisplay-data[i]">' + data[i] + '</div>';
// //var htmlStr = `${`<h2>${nameX}</h2>`}`; //using Template Literal concept
// }
// });
//choose a person to chat with
var div_ele=displayUsers.childNodes;
socket.on('usernames', function(data){
displayUsers.innerHTML = '';
var htmlStr = '';
for(var i=0; i<data.length; i++){
htmlStr = '<p>' + data[i]+'</p>';
var innerDisplayUsers = document.createElement('div');
innerDisplayUsers.id = data[i];// + '-innerDisplayUser';
innerDisplayUsers.innerHTML = htmlStr;
displayUsers.appendChild(innerDisplayUsers);
}
for (var i=0; i<div_ele.length; i++) {
//console.log(div_ele[i]);
div_ele[i].addEventListener('click', chooseUserToChatWith(div_ele[i]));
}
});
function chooseUserToChatWith(data){
return function(){
console.log(data); console.log(data.id);
chatDivContainer.style.display = "block";
sendMessageToUser(data.id);
};
}
//send message to chosen client
function sendMessageToUser(client) {
console.log(client);
chatBtn.addEventListener('click', function(e) { e.preventDefault();
socket.emit('send message', { 'client': client, 'msg': msg.value} );
msg.value = '';
});
}
//add event listener on msg typing
msg.addEventListener('keypress', function(){
socket.emit('typing message', userNameInput.value);
});
//message output
socket.on('new message', function(data){
chatDivContainer.style.display = "block";
typingOutput.innerHTML="";
var htmlStr = '';
htmlStr += '<p>' + data.sender +': '+ data.message + '</p>';
var innerChatOutput = document.createElement('div');
innerChatOutput.id = data.client;
innerChatOutput.innerHTML = htmlStr;
chatOutput.appendChild(innerChatOutput);
//keep scroll on bottom
var xH = chatMessagesContainer.scrollHeight;
chatMessagesContainer.scrollTo(0, xH);
});
//Listen on events
// socket.on('new message', function(data){
// chatDivContainer.style.display = "block";
// typingOutput.innerHTML="";
// chatOutput.innerHTML += '<p>' + data.sender +': '+ data.message + '</p>';
// //keep scroll on bottom
// var xH = chatMessagesContainer.scrollHeight;
// chatMessagesContainer.scrollTo(0, xH);
// });
socket.on('typing message', function(data){
console.log(data + ' typing message')
typingOutput.innerHTML = '<p>' + data + ' is typing message...</p>';
});
//SERVER JS file
//A Server File, all console.log() will be printed in terminal window
//Server setup
var express = require('express'),
app = express(), //simply one line var app = require('express')();
server = require('http').createServer(app),
usersNames = {},
io = require('socket.io').listen(server);
server.listen(3000, function(){ console.log('listening port 3000')});
//Express Routing as soon as we go to http://host:port this page will be served
// app.get('/', function(req, res){
// res.sendFile(__dirname + '/index.html');
// });
app.use(express.static('public'));
//listen on events client side
io.sockets.on('connection', function(socket) {
//user enters onto chat
socket.on('new user', function(data, callback){
if(data in usersNames) { callback(false); }
else {
callback(true);
socket.userName = data;
usersNames[socket.userName] = socket; //userName is key : socket
updateUsersNames();
}
});
//usersNames object keys updated
function updateUsersNames() {
io.sockets.emit('usernames', Object.keys(usersNames));
}
//if user leaves chat, then username removed from UsersNames[]
socket.on('disconnect', function(data){
if(!socket.userName) return; //if there s no username simply return
delete usersNames[socket.userName];
updateUsersNames();
});
//user sends message from clientside
socket.on('send message', function(obj){
console.log(obj.client);
socket.broadcast.to(obj.client).emit('new message', {
// io.sockets.emit('new message', {
sender: socket.userName,
message: obj.msg,
client: obj.client
});
});
socket.on('typing message', function(data){
socket.broadcast.emit('typing message', socket.userName); //server sends msg to all excluding me
});
});
我尝试过的事情:
我真的停留在这里,希望比我聪明的人可以帮忙
PM CHAT的构建思路是每个人都可以通过单击用户名来彼此实现PM.
可以说亚历克斯(Alex),凯特(Kate),大卫(David)进入PMchat.
Alex单击Kate并向她发送私人消息,
soAlex向KAte发送了一条消息,因此只有Kate可以看到从ALex收到的消息,其他人都没有,这在这里没有发生,我有点卡住了
What I have tried:
im really stuck on here, hope someone who is more clever than me can do a help please
PM CHAT construction idea was each person can PM to each other by clicking on the username.
lets say Alex, Kate, David enters PMchat.
Alex clicks on Kate and sends private message to her,
soAlex sends a message to KAte, so Only Kate can see the message received from ALex, nobody else, this is not happening here, im bit stuck
used pure javascript, socket io, node js, express module, css/html.
推荐答案
这篇关于Socket io私人消息传递问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!