与socket.io建立聊天,我遇到了一个似乎对我来说很基本的错误,但我找不到答案。
我检查了类似的答案,例如 socket-io-multiple-chats-on-one-page socket-io-multiple-connections-when-refreshing-page node-js-socket-io-page-refresh-multiple-connections 与上面的主要区别是控制台中连接的插槽数正确。 我还尝试了node-js-socket-io-page-refresh-multiple-connections
的解决方案var socket = io({transports: ['websocket'], upgrade: false});
但没有结果。我还尝试了房间和名称空间。
io.sockets.on('connection', function (socket) {
socket.on('subscribe', function(data) { socket.join(room); })
socket.on('unsubscribe', function(data) { socket.leave(room); })
socket.on("newchatsent", function (msg) {
//save chat to mongo
MongoClient.connect(url, {useNewUrlParser: true}, function (err, client) {
if (err) {
console.error('An error occurred connecting to MongoDB: ', err);
} else {
var db = client.db(database);
var collection = db.collection("chat");
collection.updateOne({"cid": cid},{
$push: {"chat": {u: who, c: msg, t: timestamp}},
"$inc": {"total": 1}, "$inc": {[unread]: 1}
}, function (err, result) {
if (err) {
console.log(err);
} else {
//emit data to frontend
socket.emit("newchatreply", msg);
client.close();
}
assert.equal(err, null);
});
}
});
});
});
var socket = io({transports: ['websocket'], upgrade: false});
socket.emit("subscribe", room);
$(document).on('keypress', function (e) {
if (e.which == 13 && $("#chatText").is(":focus")) {
var mes = $('#chatText').val().trim();
if (mes != "") {
socket.emit('newchatsent', mes);
$('#chatText').val('');
return false;
}
}
});
socket.on('newchatreply', function(msg){
$( "#chati" ).append( "<div id='chatLine'><p class='triangle-isosceles right'>"+ msg +"</p>" +
"<div class='chatDatetime'>"+date('Y-m-d H:i')+"</div></div>");
});
给出Sriram Kailasam:问题是,每次重新加载页面时,您都在注册一个新的事件处理程序。这将导致数据被发送多次。我遇到了同样的问题,我通过在服务器中使用io.once()
而不是io.on()
来解决了这个问题。