簡體   English   中英

服務器崩潰,重新啟動時發送消息(Node.js / Socket.io)

[英]Server crash, sending message at restart (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的東西:)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM