有没有办法在Node.js网(套接字)库中更改“on”侦听器?

时间:2015-11-24 12:14:09

标签: javascript node.js sockets tcp

我正在使用Node.js的net library来设置基本的TCP套接字连接:

socket.on("data")

有没有办法在不关闭连接的情况下删除或更改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); 侦听器?我尝试了显而易见的事情:

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

当我从客户端连接时:

socket to me: boom!

按预期打印socket to me: boom! ouch 。但下一个写输出:

$ cordova plugin add https://github.com/boltex/cordova-plugin-powermanagement.git

有没有办法改变第一个监听器,或者删除它并用另一个监听器替换它?

2 个答案:

答案 0 :(得分:2)

事实证明,直接编辑套接字的_events对象可以让你换出监听器,即使它们是匿名的。例如:

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);

然后在客户端:

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

输出:

socket to me: boom!
ouch

以为我会在这里分享一下,以防它对其他人有用!

答案 1 :(得分:1)

如何在侦听器中使用条件?

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);