javascript - 服务器崩溃,重启时发送消息(Node.js/Socket.io)

标签 javascript node.js socket.io

大家好,我正在做一个消息系统,一切正常,但现在我想添加一点,如果服务器崩溃并重新启动,在此期间发送的消息将在服务器重新启动时发送。我试图在客户端保存消息的信息,并制作一个等待服务器响应的“等待”系统。所以我想知道我该如何做那个“等待”系统,因为现在我正在这样做:

while (socket.connected === false) {
}

但这会使客户端出现错误,因为无限循环太快了……那么是否可以设置一个计时器? (我已经尝试过,但我没有找到如何在循环中制作一个好的计时器)。

或者也许我完全错了,我没有做一个等待系统,而是另一件事所以告诉我我的技术是否行不通或者是否有更好的:)

这是我的代码:

Client.js(有人连接时调用startTchat)

(function($){

var socket = io.connect('http://localhost:1337');
var lastmsg = [];
var me_id = [];
var friend_ = [];
var conv_ = [];
var isPlace_ = [];
var isLocation_ = [];
var me_ = [];
var my_id;

startTchat = function(user_id, username, friend_id, conv_id, isPlace, isLocalisation) {
    my_id = user_id;
    socket.emit('login_chat', {
        id : user_id,
        username : username,
        friend : friend_id,
        conv : conv_id,
        isPlace : isPlace,
        isLocalisation : isLocalisation,
    })
};

/**
 * Error
 */
socket.on('error', function(err){
    alert(err);
});

/**
 * Messages
 */
$('#chat_form').submit(function(event){
    var a = 0;
    while (socket.connected === false) {
    }
    event.preventDefault();
    console.log('ME', my_id, 'TAB', me_id);
    socket.emit('new_msg', {message: $('#message').val() }, me_id[my_id], friend_[my_id], conv_[my_id], isPlace_[my_id], isLocation_[my_id], me_[my_id]);
    if (a === 1) {
        console.log('HEYYYYYYYYYY', my_id);
    }
    $('#message').val('');
    $('#message').focus();
});

socket.on('new_msg', function(message, me, id_receiver, id_transmiter){
    if (me.id === id_receiver || me.id === id_transmiter) {
        if (lastmsg != message.user.id) {
            $('#new_message').append('<span class="time_date"> ' + message.h + ' : ' + message.m + ' | ' + message.y + '-' + message.m + '-' + message.d + ' | ' + message.user.username + '</span>'
                + '<p>' + message.message + '</p>\n'
            );
            lastmsg = message.user.id;
        } else {
            $('#new_message').append('<p>' + message.message + '</p>'
            );
        }
    }
});


/**
 * Login
 */
socket.on('new_user', function(user, friend, conv, isPlace, isLocation){
        me_id[user.id] = user.id;
        friend_[user.id] = friend;
        conv_[user.id] = conv;
        isPlace_[user.id] = isPlace;
        me_[user.id] = user;
        isLocation_[user.id] = isLocation;
    $('#new_user').append('<div class="chat_list active_chat" id="' + user.id + '">\n' +
        '                        <div class="chat_people">\n' +
        '                            <div class="chat_img"> <img src="https://ptetutorials.com/images/user-profile.png" alt="sunil"> </div>\n' +
        '                            <div class="chat_ib">\n' +
        '                                <h5>' + user.username + ' <span class="chat_date">Id : ' + user.id + '</span></h5>\n' +
        '                            </div>\n' +
        '                        </div>\n' +
        '                    </div>');
});


/**
 * Disconnect
 */
socket.on('disc_user', function(user){
    $('#' + user.id).remove();
})

})(jQuery);

和 server.js :

var http = require('http');
var MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'msg';

MongoClient.connect(url, function(err, client) {

if (err)
    throw err;
console.log('MongoDB connected ...');

httpServer = http.createServer(function(req, res) {
    console.log('This is a test');
    res.end('Hello World');
});

httpServer.listen(1337);

var io = require('socket.io').listen(httpServer);
var users = {};
var messages = [];

io.sockets.on('connection', function (socket) {

    const collection = client.db(dbName).collection('MessageUser');

    var me = false;
    var friend = false;
    var conv = false;
    var isPlace = false;
    var room = false;
    var isLocalisation = false;

    for(var k in users) {
        socket.emit('new_user', users[k]);
    }

    /**
     * Login
     */
    socket.on('login_chat', function (user) {
        me = user;
        friend = user.friend;
        isPlace = user.isPlace;
        conv = user.conv;
        isLocalisation = user.isLocalisation;
        if (isPlace === 0) {
            room = user.conv;
        } else {
            room = user.conv + '-Place';
        }
        socket.join(room);
        //console.log('New user : ', me.username, ' - id : ', me.id);
        users[me.id] = me;
        io.sockets.emit('new_user', me, friend, conv, isPlace, isLocalisation);
    });

    /**
     * Disconnect
     */
    socket.on('disconnect', function() {
        if (!me) {
            return false;
        }
        delete users[me.id];
        io.sockets.emit('disc_user', me);
    });

    /**
     * Message receive
     */
    socket.on('new_msg', function(message, me_id, friend_, conv_, isPlace_, isLocalisation_, me_){
        if (message.message !== '') {
            message.user = me;
            date = new Date();
            message.h = date.getHours();
            message.m = date.getMinutes();
            message.y = date.getFullYear();
            message.m = date.getMonth();
            message.d = date.getDate();
            console.log(message);
            messages.push(message);
            msg = {};
            msg.content = message.message;
            msg.sendAt = new Date();
            msg.idTransmitter = me.id;
            if (isPlace === 0) {
                msg.idReceiver = friend;
            } else {
                msg.idReceiver = conv;
            }
            msg.idConversation = conv;
            msg.isPlace = isPlace;
            msg.isLocalisation = isLocalisation;
            collection.insertOne(msg);
            console.log('---1---', msg.idReceiver, '---2---', msg.idTransmitter, '---3---', me);
            io.to(room).emit('new_msg', message, me, msg.idReceiver, msg.idTransmitter);
        }
    });
});
});

ps :如果您需要更多信息,请告诉我,如果我忘记了我第一次使用 js、node 和 socket.io 的东西,抱歉 :)

最佳答案

while (socket.connected === false) {
}

不要这样做,它会阻止您的页面并使您的处理器占用 100%。
相反,请使用 setTimeout。它相当于 javascript 中的 sleep。您需要重构您的代码,以递归方式调用 setTimeout,并计算“重试”次数(如果您想在某个时间点停止)。

代码:

$('#chat_form').submit(function(event){
    var retries = 0, max_retries = 10;

    function tryNewMessage() {
       if (socket.connected === false) {
          if (retries >= max_retries) return; //handle max_retries properly in your code

          //this is where you sleep for 1 second, waiting for the server to come online
          setTimeout(tryNewMessage, 1000);
          retries++;
       }
       else {
         var a = 0;

         event.preventDefault();
         console.log('ME', my_id, 'TAB', me_id);
         socket.emit('new_msg', {message: $('#message').val() }, me_id[my_id], friend_[my_id], conv_[my_id], isPlace_[my_id], isLocation_[my_id], me_[my_id]);
         if (a === 1) {
           console.log('HEYYYYYYYYYY', my_id);
         }
         $('#message').val('');
         $('#message').focus();
       }
    }

    tryNewMessage();
});

关于javascript - 服务器崩溃,重启时发送消息(Node.js/Socket.io),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53060694/

相关文章:

javascript - 如何从网页Javascript调用C#方法?

javascript - 如何使用 DDP 从 Meteor 服务器接收流

javascript - 输出国家代码到控制台

node.js - 慢速磁盘 I/O 是否会降低 Node.js 应用程序其余部分的性能?

Node.js 多服务器集群 : how to share object in several nodes cluster

javascript - 为什么 `enable-javascript-harmony` 会阻止 Web Worker 中的 Stack Overflow?

json - 无法获取 JSON 对象的长度

javascript - AJAX 发送数据到 Node.js 服务器

tomcat - 如何在 Tomcat 7 上实现 Socket.io

javascript - 如何使用socket.io实现生存时间