如何在使用Socket.io,NodeJS完成页面刷新之前断开连接并且不重新连接

时间:2017-01-13 14:03:42

标签: javascript node.js socket.io

我正在处理一个任务,我使用带有socket.io,express和mysql-events node.js模块的Node.js,每当新记录插入表中时都会发出数据。

我已完成所有与发射和显示的连接,但我正面临页面刷新问题。当我试图点击另一个链接或我将刷新页面时,如果node.js服务器正在运行并连续发送数据,则需要花费大量时间来打开或刷新链接。但是当node.js没有运行时就没有问题了。

我试图断开页面重新加载事件,但这对我没有帮助。

更新

// server.js that running on server side.

var app = require('express')();
var compression = require('compression');
app.use(compression());
var http = require('http').Server(app);
var io = require('socket.io').listen(http, {
  'transports': [
      'websocket'
    , 'flashsocket'
    , 'htmlfile'
    , 'xhr-polling'
    , 'jsonp-polling'
  ],
  'close timeout': 60,
  'heartbeat timeout': 60,
  });

var mysql = require('mysql');
var MySQLEvents = require('mysql-events');
var request = require('request');


var dsn = {
    host: 'localhost',
    user: 'root',
    password: 'tester'
};

var mysqlPool = mysql.createPool({
    connectionLimit : 25,
    host: 'localhost',
    port: 3306,
    user: 'root',
    password: 'tester',
    database: 'test'
});
var myCon = MySQLEvents(dsn, {
  startAtEnd: false, // it overrides default value "true"
  includeEvents: ['writerows'],
  includeSchema: {'test': ['ttest']},
});

var barCols = [], barRows = [];
var pieCols = [], pieRows = [];
var jsonBarChart, jsonPieChart;

http.listen(3000, function(){
    console.log('Listening on Port 3000');
});

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


//  console.log("====================== Connected ======================" +socket.id);
     var event1 = myCon.add(
      'test.ttest',
      function (oldRow, newRow) {
        if(newRow !== null){
            var data = {
                dd: newRow.fields,
            };
            io.emit('my-channel', data);

//      try {
//          global.gc();
//        } catch (e) {
//          console.log("You must run program with 'node --expose-gc index.js' or 'npm start'");
//          process.exit();
//        }
        }
      }
    );
     myCon.stop();
});

// index.html客户端。

var socket = null;
    $(window).bind('beforeunload',function(){
        socket.disconnect();
    });

    $(document).ready(function(){
        var connectionOptions =  {
                "force new connection" : true,
                "reconnection": true,
                "reconnectionDelay": 2000,                  //starts with 2 secs delay, then 4, 6, 8, until 60 where it stays forever until it reconnects
                "reconnectionDelayMax" : 60000,             //1 minute maximum delay between connections
                "reconnectionAttempts": "Infinity",         //to prevent dead clients, having the user to having to manually reconnect after a server restart.
                "timeout" : 10000,                           //before connect_error and connect_timeout are emitted.
                "transports" : ['websocket', 'polling']                //forces the transport to be only websocket. Server needs to be setup as well/
        }

        socket = io('http://10.3.3.141:3000', connectionOptions);
        socket.on('open', function(){ console.log("Client Open a connection.");});

        socket.on('connect', function(){ 
            console.log("Client Connected.");

            socket.on("my-channel", function(msg){ 
                if(msg == null){
                    console.log("MSG is Null");
                    return;
                }

                var activityItem = '<div class="table-row"><div class="table-cell">'+msg.dd.ipaddress+'</div></div>';
                $("#activity-threat-body").prepend(activityItem);
                $("#activity-threat-body>.table-row:nth-child(6)").remove();
            });

        });
        socket.on('connect_timeout', function(){ console.log("Client Connection timeout.");});
        socket.on('connect_error', function(){ 
            console.log("Client connection error.");
            socket.connect();
        });
        socket.on('reconnect_attempt', function(){ console.log("Client reconnect attempt.");});
        socket.on('reconnect', function(){console.log("Client Reconnected.");});
        socket.on('reconnect_error', function(){ console.log("Client Reconnect Error.");});
        socket.on('reconnect_failed', function(){ console.log("Client Reconnect Failed.");});
        socket.on('close', function(){ console.log("Client connection closed.");});
        socket.on('disconnect', function(){
           console.log("Client Disconnected");
           socket.connect();
        });

    });

0 个答案:

没有答案