Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/458.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 服务器崩溃,重新启动时发送消息(Node.js/Socket.io)_Javascript_Node.js_Socket.io - Fatal编程技术网

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

Javascript 服务器崩溃,重新启动时发送消息(Node.js/Socket.io),javascript,node.js,socket.io,Javascript,Node.js,Socket.io,嘿,伙计们,我正在做一个消息系统,所有的工作都很好,但现在我想补充一点,如果服务器崩溃并重新启动,在这段时间内发送的消息将在服务器重新启动时发送。我试图将消息的信息保存在客户端,并创建一个等待服务器响应的“等待”系统。所以我想知道我如何才能做到“等待”系统,因为现在我是这样做的: while (socket.connected === false) { } 但这会让bug成为客户端,因为无限循环太快了。。。那么可以设置一个计时器吗?(我已经试过了,但我找不到如何在循环中制作一个好的计时器) 或

嘿,伙计们,我正在做一个消息系统,所有的工作都很好,但现在我想补充一点,如果服务器崩溃并重新启动,在这段时间内发送的消息将在服务器重新启动时发送。我试图将消息的信息保存在客户端,并创建一个等待服务器响应的“等待”系统。所以我想知道我如何才能做到“等待”系统,因为现在我是这样做的:

while (socket.connected === false) {
}
但这会让bug成为客户端,因为无限循环太快了。。。那么可以设置一个计时器吗?(我已经试过了,但我找不到如何在循环中制作一个好的计时器)

或者我完全错了,我没有做等待系统,但还有一件事,所以告诉我我的技术是否不起作用,或者是否有更好的:)

这是我的代码:

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

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

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

代码:

(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);
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);
        }
    });
});
});
while (socket.connected === false) {
}
$('#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();
});