Skip to content

Instantly share code, notes, and snippets.

@erikbrannstrom
Created June 9, 2017 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikbrannstrom/37a3d2c73ce6616cab87f0847705ce93 to your computer and use it in GitHub Desktop.
Save erikbrannstrom/37a3d2c73ce6616cab87f0847705ce93 to your computer and use it in GitHub Desktop.
/*
I can't seem to override net.Socket.write.
Expected output:
> Sending...
> Ending socket...
> Server received data: test write
> test end
Actual output:
> Ending socket...
> Server received data: test write
> test end
Am I missing something?
*/
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");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment