无法覆盖net.Socket.write

时间:2017-06-13 06:28:52

标签: node.js

我似乎无法覆盖net.Socket.write。下面的示例不是我的真实用例,而是一个缩小的,可运行的示例来演示此问题。

const net = require("net");

class UTF8Socket extends net.Socket {
    constructor () {
        super();
        this.setEncoding("utf8");
    }

    write(data, cb) {
        console.log("Sending...");
        super.write(data, "utf8", cb);
    }

    end(data) {
        console.log("Ending socket...");
        super.end(data);
    }
}

// Setup server
const server = net.createServer(socket => {
    socket.setEncoding("utf8");
    socket.on("data", (res) => console.log("Server received data:", res));
});
server.listen(8080, '127.0.0.1');

// Create a UTF8Socket and write to server
const socket = new UTF8Socket();
socket.connect(8080, "127.0.0.1", () => {
    socket.write("test write\n");
    socket.end("test end");
});

预期输出:

  

发送...

     

结束插座...

     

服务器收到数据:test write

     

测试结束

实际输出:

  

结束插座...

     

服务器收到数据:test write

     

测试结束

从输出中可以看到被覆盖的结束函数,但只调用了原始的net.Socket.write。我觉得我错过了一些东西......

1 个答案:

答案 0 :(得分:1)

我想这是因为net.Socket.connect()的实施中of this code

if (this.write !== Socket.prototype.write)
  this.write = Socket.prototype.write;

可能的解决方法:

connect() {
  let result = super.connect.apply(this, arguments);
  this.write = UTF8Socket.prototype.write.bind(this);
  return result;
}