您好,我已经使用 socket.io、expressjs 和 mongoose 开发了聊天应用程序,它运行良好。它会在几秒钟后刷新并从数据库中获取新客户端(如果存在)。问题是用户可以感觉到 div 正在刷新。而且还需要一些时间来响应。如何避免这种情况。这是我的代码 这是我的服务器端代码
setInterval(function () {
var allOnLine;
allOnLine = io.sockets.clients();
for (var client in allOnLine) {
if (allOnLine[client].username == "undefined") {
continue;
} else {
notifyAll(allOnLine[client].username);
}
}
}, 50000);
这是通知所有方法
function notifyAll(userName) {
contactModel.find({'userId':userName}, (function (err, contactModel) {
usernames = [];
var contacts = contactModel;
for (var a = 0; a < contacts.length; a++) {
usernames[a] = contacts[a].contactId;
}
var allOnLine;
allOnLine = io.sockets.clients();
for (var client in allOnLine) {
if (allOnLine[client].username == "undefined") {
continue;
} else {
for (var i = 0; i < usernames.length; i++) {
if (allOnLine[client].username == usernames[i]) {
usernames[i] = usernames[i] + " -On";
}
allOnLine[client].username);
}
}
}
io.sockets.to(userName).emit('updateusers', usernames);
}));
}
这是我的客户代码
socket.on('updateusers', function(usernames) {
jQuery('#usernames').html('');
jQuery.each(usernames, function(key, value) {
jQuery('#usernames').append('<div class="chatContact" id="chatLink" onclick="privateChat(\''+value+'\')">' );
}}
任何帮助我也发布了这个问题但没有答案