我一直在关注使用socket.io mongodb和nodejs构建聊天应用程序的视频教程。我完成教程并构建教程中的相同聊天应用程序。但是当我打开两个或更多选项卡时然后最新打开的标签工作完美,但其他较旧的标签不能完美地工作...当我输入消息并按Enter键然后我的文本区域中的消息不清除,它也不显示“消息”的状态消息发送“..并在当前新标签上显示此状态..如何解决此问题请帮助我....我还通过本地主机运行应用程序...在视频中,应用程序已部署按文件系统。
我的Server.js文件是..
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
connections = [];
server.listen(process.env.PORT || 4000);
console.log('Server running....');
app.get('/',function(req,res){
res.sendFile(__dirname + '/index.html');
});
const mongo = require('mongodb').MongoClient;
//const client = require('socket.io').listen(4000).sockets;
//connect to mongo
mongo.connect('mongodb://127.0.0.1/mongochat',function(err,db){
if(err){
throw err;
}
console.log('MongoDB Connected...');
//Connect to socket.io
io.sockets.on('connection',function(socket){
connections.push(socket);
console.log('Connected %s sockets connected', connections.length);
let chat = db.collection('chats');
//Create function to send status
sendStatus = function(s){
socket.emit('status',s);
}
//Get All chats from mongo collection
chat.find().limit(100).sort({_id:1}).toArray(function(err,res){
if(err){
throw err;
}
socket.emit('output',res);
});
//Handle input from clients
socket.on('input',function(data){
let name = data.name;
let message = data.message;
if(name=='' || message==''){
//Send Error Status
sendStatus('Please enter a name and message');
}
else{
//Insert messages to MongoDB
chat.insert({name: name, message: message},function(){
io.emit('output',[data]);//client
//Send status object
sendStatus({
message: 'Message sent',
clear: true
})
});
}
});
//Handle clear button
socket.on('clear',function(data){
//Remove all chats from collection
chat.remove({},function(){
//Emit Cleared
socket.emit('cleared');
});
});
});
});
Index.html file is..
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<title>LiveChat</title>
<style>
#messages{
height: 300px;
}
.card-block{
white-space: nowrap;
overflow: hidden;
overflow-y: auto;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3 col-sm-12">
<h1 class="text-center">LiveChat
<button id="clear" class="btn btn-danger">Clear</button>
</h1>
<div id="status"></div>
<div id="chat">
<input type="text" id="username" class="form-control" placeholder="Enter name...">
<br>
<div class="card">
<div class="card-block" id="messages">
</div>
</div>
<br>
<textarea id="textarea" class="form-control" placeholder="Type message..."></textarea>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js">
</script>
<script>
(function(){
var element = function(id){
return document.getElementById(id);
}
//Get Elements
var status = element('status');
var messages = element('messages');
var textarea = element('textarea');
var username = element('username');
var clearbtn = element('clear');
//Set default status
var statusDefault = status.textContent;
var setStatus = function(s){
//Set status
status.textContent = s;
if(s!==statusDefault){
var delay = setTimeout(function(){
setStatus(statusDefault);
},4000);
}
}
//Connect to socket.io
var socket = io.connect('http://127.0.0.1:4000');
//Check for connection
if(socket !== undefined){
console.log('Connected to socket...');
//Handle output
socket.on('output',function(data){
console.log(data);
if(data && data.length>0){
for(var x = 0; x < data.length;x++){
//Build out message div
var message = document.createElement('div');
message.setAttribute('class','chat-message');
message.innerHTML = '<strong>'+data[x].name+'</strong>: '+data[x].message;
//message.textContent = data[x].name+": "+data[x].message;
messages.appendChild(message);
messages.insertBefore(message,messages.firstChild);
}
}
});
//Get Status from Server
socket.on('status',function(data){
//get message status
setStatus((typeof data ==='object')?data.message : data);
//If status is cleared,clear text
if(data.clear){
textarea.value = '';
}
});
//Handle Input
textarea.addEventListener('keydown',function(event){
if(event.which === 13 && event.shiftKey == false){
//Emit to server
socket.emit('input',{
name:username.value,
message:textarea.value
});
event.preventDefault();
}
});
//Handle Clear Button
clearbtn.addEventListener('click',function(){
socket.emit('clear');
});
//Clear Message
socket.on('cleared',function(){
messages.textContent = '';
});
}
})();
</script>
</body>
</html>