我正在尝试使用Socket.io
实施聊天服务。在开发模式下运行服务器一小段时间后,每当我尝试发送消息时,它都会复制我的消息(尤其是当我按Enter键时)。如何防止遇到这个问题?
除以下错误外,没有其他错误:
MaxListenersExceededWarning:检测到可能的EventEmitter内存泄漏。添加了11个newMessage侦听器。使用generator.setMaxListeners()增加限制
这是我的代码:
server.js
var io = require('socket.io')(8081);
router.get('/chat', (req, res) => {
if (req.session.userId) {
teamName = req.session.teamName;
faculty = req.session.faculty;
console.log(teamName, faculty)
io.on('connection', (socket) => {
// Save new Messages to DB and show on the page
socket.on('newMessage', message => {
io.emit('newMessage', message)
teamName = req.session.teamName;
faculty = req.session.faculty;
if (teamName && faculty) {
if (message != "") {
var newChatMessage = {
teamName: teamName,
faculty: faculty,
message: message
}
Chat.create(newChatMessage, (err, newChat) => {
if (err) {
console.log('[Chat Error]: ', err)
} else {
console.log(newChat)
}
})
}
}
})
});
// Get chats from mongoDB
Chat.find({faculty: faculty}, (err, chatHistory) => {
if (err) {
console.log(err)
}
else {
io.emit('messageHistory', chatHistory);
console.log(chatHistory)
res.render('main/chat', {
messages: chatHistory,
faculty: faculty,
teamName: teamName
})
}
})
}
else {
res.redirect('/')
}
});
字体结尾:
<script>
$(function() {
var socket = io('http://localhost:8081');
$('#sendMessage').on('click', function() {
var newMessage = $('#m').val()
if (newMessage != ""){
socket.emit('newMessage', $('#m').val());
$('#m').val('');
return false
}
})
socket.on('newMessage', function(message) {
$('#messages').append($('<li>').text(message));
window.scrollTo(0, document.body.scrollHeight);
})
})
</script>