Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to change the "on" listeners in the Node.js net (Sockets) library?

I'm using Node.js's net library to set up a basic TCP socket connection:

net.createServer(function (socket) {
    socket.on("data", function (data) {
        console.log("socket to me:", data);
    });
}).listen();

Is there a way to remove or change the socket.on("data") listener, without closing the connection? I tried the obvious thing:

net.createServer(function (socket) {
    socket.on("data", function (data) {
        console.log("socket to me:", data.toString());
        socket.on("data", function (data) {
            console.log("ouch");
        });
    });
}).listen(10101);

When I connect from the client:

var client = net.connect({host: "localhost", port: 10101});
client.write("boom!");

It prints socket to me: boom!, as expected. But the next write outputs:

socket to me: boom!
ouch

Is there any way to alter the first listener, or remove it and replace it with a different one?

like image 656
tinybike Avatar asked Sep 16 '25 07:09

tinybike


2 Answers

It turns out that editing the socket's _events object directly lets you swap out listeners, even if they're anonymous. For example:

net.createServer(function (socket) {
    socket.on("data", function (data) {
        console.log("socket to me:", data.toString());
        socket._events.data = function (data) {
            console.log("ouch");
        };
    });
}).listen(10101);

And then in the client:

var client = net.connect({host: "localhost", port: 10101});
client.write("boom!");
client.write("boom!");

Outputs:

socket to me: boom!
ouch

Just thought I'd share this here, in case it's useful to anyone else!

like image 135
tinybike Avatar answered Sep 17 '25 21:09

tinybike


How about using a conditional inside the listener?

var firstExecution = true;

net.createServer(function (socket) {

    socket.on("data", function (data) {

        if (firstExecution) {
            console.log("socket to me:", data.toString());
            firstExecution = false;
        }
        else {
            console.log("ouch");
        }
    });
}).listen(10101);
like image 24
Mehdi Avatar answered Sep 17 '25 21:09

Mehdi