0

I have a web server run by node.js It uses Express, Socket.io, and MySQL

I use socket.io to transmit data from client to server, and also to call queries.

After implementing SQL connexion and queries, the server started to stop after exactly 60 seconds running it.

SQL part in the index.js file:

// SQL

var mysql = require('mysql');
var con = mysql.createConnection({
    host: "...",
    user: "...",
    password: "...",
    database: "..."
});

//Socket.io

var io = require('socket.io') (serv, {});
io.sockets.on('connection', function(socket) {

    // Select

    socket.on("recherche", function(data) {
            if (err) throw err;
            con.query("SELECT * FROM ..", function (err, result, fields) {
                if (err) throw err;
                socket.emit("...", {data: result});
            });
    });

    // Insert into

    socket.on("...", function(data) {
        con.connect(function(err) {
            if (err) throw err;
            var sql = "INSERT INTO ... VALUES (...)";
            con.query(sql, function (err, result) {
                if (err) throw err;
                console.log("1 record inserted");
            });
        });
    });

});

Everything is working just fine for 60 second after start the server. Then, I have this error message in the nodejs console:

C:\Users\...>node index.js
events.js:187
throw er; // Unhandled 'error' event
^
...
Error: Connection lost: The server closed the connection.
...
fatal: true,
code: 'PROTOCOL_CONNECTION_LOST'

Thank you in advance to read my question :D

Pazu
  • 171
  • 3
  • 8
  • increase the timeout on server side https://stackoverflow.com/a/19610568/5193536 pr use await and promises, which waits till a response has come see https://stackoverflow.com/questions/44004418/node-js-async-await-using-with-mysql/51690276 – nbk Dec 06 '19 at 14:05

1 Answers1

0
          connection = mysql.createConnection(db_config); // Recreate the connection, since

          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') { // Connection to the MySQL server is usually
              handleDisconnect();                        
            } else {                                     
              throw err;                                 
            }
          });
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – dw_ Dec 06 '19 at 13:40