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

时间:2018-10-30 09:04:17

标签: javascript node.js socket.io

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

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

但是那会使bug成为客户端,因为无限循环太快了……所以可以设置一个计时器吗? (我已经尝试过了,但是我没有找到如何使一个好的计时器循环播放)。

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

这是我的代码:

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的东西:)

1 个答案:

答案 0 :(得分:0)

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();
});