节点js将db错误称为'PROTOCOL_CONNECTION_LOST'

时间:2016-03-31 05:04:21

标签: node.js socket.io

我使用节点js和socket io开发了一个聊天应用程序。但它工作正常5到10分钟。但在那之后我继续犯错误

db error { [Error: Connection lost: The server closed the connection.] fatal: true, code: 'PROTOCOL_CONNECTION_LOST' }

我使用下面给出的代码重新连接,但它仍然给我同样的错误。

var app = require('express')();
app.set('port', process.env.PORT || 3000);
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = app.get('port');
var mysql = require('mysql');



var db_config = {
  	host     : 'localhost',
	user     : 'root',
	password : '',
	database : 'chatapp'
};


var connection;

function handleDisconnect() {
  connection = mysql.createConnection(db_config); 
  connection.connect(function(err) {              
    if(err) {                                     
      console.log('error when connecting to db:', err);
      setTimeout(handleDisconnect, 2000); 
    }                                     
  });                                     
                                          
  connection.on('error', function(err) {
    console.log('db error', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') { 
      handleDisconnect();                         
    } else {                                      
      throw err;                                  
    }
  });
}

handleDisconnect();

0 个答案:

没有答案