var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
var mysql = require('mysql');
app.get('/', function(req, res){
res.send('<h1>My App</h1>');
});
var db_config = {
host: 'localhost',
user: 'root',
database: 'database',
password: '',
dialect: 'mysql',
insecureAuth: true
};
var connection;
function handleDisconnect() {
connection = mysql.createConnection(db_config); // Recreate the connection, since
// the old one cannot be reused.
connection.connect(function(err) { // The server is either down
if(err) { // or restarting (takes a while sometimes).
console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
} // to avoid a hot loop, and to allow our node script to
}); // process asynchronous requests in the meantime.
// If you're also serving http, display a 503 error.
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
handleDisconnect(); // lost due to either server restart, or a
} else { // connnection idle timeout (the wait_timeout
throw err; // server variable configures this)
}
});
}
handleDisconnect();
http.listen(3000, function(){
console.log('listening on *:3000');
});
.............
I am developing an app that returns real time score updates from database as shown in the code above. When I execute the program above with localhost (wamp) it works fine. When executing with CentOS 7 with MariaDB it returns an error stating:
db error { Error: Connection lost: The server closed the connection.
I have done some changes to my code by following this thread. But it didn't work. And also I tried with Pooling also. Help me to resolve this issue.