Node restart UDP server

I am creating an udp server to receive a message and send a response quickly.

However, I have a problem: the server cannot close the connection with the client after its response.

So, in order to avoid server saturation, I thought about how to restart the udp server (like reconnecting) as soon as the counter reaches a certain number, but I can not find a solution to close the udp server and restart it.

Is there any way to do this?

Here is an example code snippet of what I have at the moment:

/** Udp server */
var reset = function() {
    if(count > 3) {
        server.close();
        count = 0;
        console.log('reset');
        server.bind('4002');
    }
    return true;
};
var count = 0;
var server = require("dgram").createSocket("udp4");
server.on("message", function(message, requestInfo) {
        count++;
        message = message.toString();
        if(message == null || message === '') {
            reset();
            return;
        }
        // do something with the received message and sends the reply ..
        var response = new Buffer(result.toString());
        server.send(response, 0, response.length, requestInfo.port, requestInfo.address);
        reset();
    }
);
server.on("error", function(error) {
    console.log(error);
    server.close();
});
server.on("listening", function() {
    var address = server.address();
    console.log("server listening " + address.address + ":" + address.port);
});

server.bind('4002');

This is the stack trace:

events.js:72
    throw er; // Unhandled 'error' event
          ^
Error: Not running
at Socket._healthCheck (dgram.js:420:11)
at Socket.bind (dgram.js:160:8)
...
+4
source share

Source: https://habr.com/ru/post/1541867/


All Articles