Home > front end >  NodeJS Socket.io unhandled error event on connection from unknown client
NodeJS Socket.io unhandled error event on connection from unknown client

Time:12-20

I run a NodeJS Socket.io http server to emit news articles to clients between 7am and 5pm. Everything works fine during the day (clients connect, disconnect without crashing the server) but sometime overnight it crashes (happens about once a week). The server is not doing anything (i.e. scraping website) overnight, so it must be the io.sockets.on('connection', function (socket) {...} part of the code that causes the crash. Also, I recently added the site to Google Search Console via <meta name="google-site-verification" content="..." /> Is it possible the Google bot ping to verify is causing the crash?

I am unable to retrieve the IP address that made the request because it crashes before anything is written to log file.

the error:

node:events:491
      throw er; // Unhandled 'error' event
      ^

Error: Parse Error: Invalid method encountered
Emitted 'error' event on Socket instance at:
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  bytesParsed: 299,
  code: 'HPE_INVALID_METHOD',
  reason: 'Invalid method encountered',
  rawPacket: Buffer(316) [Uint8Array] [
     80,  79,  83,  84,  32,  47,  71, 112, 111, 110,  70, 111,
    114, 109,  47, 100, 105,  97, 103,  95,  70, 111, 114, 109,
     63, 105, 109,  97, 103, 101, 115,  47,  32,  72,  84,  84,
     80,  47,  49,  46,  49,  13,  10,  72, 111, 115, 116,  58,
     32,  49,  50,  55,  46,  48,  46,  48,  46,  49,  58,  56,
     48,  13,  10,  67, 111, 110, 110, 101,  99, 116, 105, 111,
    110,  58,  32, 107, 101, 101, 112,  45,  97, 108, 105, 118,
    101,  13,  10,  65,  99,  99, 101, 112, 116,  45,  69, 110,
     99, 111, 100, 105,
    ... 216 more items
  ]
}

Node.js v18.12.1

Here is a simplified version of the server.js

var express = require('express')
var app = express()
var server = require('http').createServer(app)
var io = require('socket.io')(server);

/*
bunch of code that runs during the day, but not when server crashes
*/

connections = []

server.listen(80)
console.log('running')

app.get('/', function (req, res) {
    res.sendFile(__dirname   '/index.html')
})

// after the first crash, I added the try{...}catch(err){...} to try to prevent the server from crashing, but it still crashes
try{
io.sockets.on('connection', function (socket) {
    // NOTE: the server crashed before any of the below executed, so I assume its the io.sockets.on(...) abo
    
    var date = new Date();
    var dashdate = (date.getMonth()   1)   "/"   date.getDate()   "/"   date.getFullYear()   " "   date.getHours()   ':'   ("0"   date.getMinutes()).slice(-2)   ':'   ("0"   date.getSeconds()).slice(-2);
    
    console.log(dashdate) //to log date time client connected 
    console.log(socket.handshake.address) //client ip address
    console.log(socket.id) //socket id
    connections.push(socket) //push socket to array to keep list of connected clients
    console.log('connected: %s sockets connected', connections.length) //log the connection
    
    // emit to client that they are connected
    io.to(socket.id).emit('new message', { msg: 'Connected - '   date.getHours()   ':'   ("0"   date.getMinutes()).slice(-2)   ':'   ("0"   date.getSeconds()).slice(-2) , link: '' })
    
    
    // on disconnect
    socket.on('disconnect', function (data) {
        connections.splice(connections.indexOf(socket), 1);
        console.log('disconnected: %s sockets connected', connections.length);
    });

    //send message
    socket.on('send message', function (data) {
        io.sockets.emit('new message', { msg: data });
    })
    
});
}catch(err){console.log(err)}

I found somebody else posted about the same exact error but there's no info on a solution: https://github.com/Ylianst/MeshCentral/issues/4482 One reply says: ...something or someone is sending garbage data in the TLS stream and as a result the TLS connection will close. This can be caused by bots, network scanners, etc...

In the end, I don't need to block the request, but how can I handle the error so it doesn't crash server.js?

CodePudding user response:

Use process.on('uncaughtException', cb) to stop the server from crashing

process.on('uncaughtException', (err, origin) => {
 //code to log the errors
 console.log(
    `Caught exception: ${err}\n`  
    `Exception origin: ${origin}`,
  );
});

in server.js

  • Related