Mastering the Socket Half-Close Pattern
In this lesson, you will learn how to signal that you have finished sending data to a peer while keeping your connection open to receive their response.
Understanding the Half-Close
When working with TCP sockets in Node.js, we often think of a connection as either "open" or "closed." However, TCP is a full-duplex protocol, meaning data can flow in both directions independently. A "half-close" occurs when one side of the connection signals that it will no longer send any more data, effectively saying, "I’m done talking," while still remaining ready to listen.
This is distinct from fully destroying the socket. If you were to destroy the socket, you would terminate the connection immediately, potentially cutting off the other party before they finish sending their final response.
Implementation in Node.js
To perform a half-close, we use the socket.end() method. Unlike socket.destroy(), calling end() sends a FIN packet to the remote peer, notifying them that the output stream is finished. The remote peer receives an end event on their readable stream, but their connection remains open, allowing them to finish sending their own data back to you.
const net = require('net');
const client = net.connect({ port: 8080 }, () => {
console.log('Connected to server.');
// Send our payload
client.write('Here is the data chunk 1...');
client.write('Here is the data chunk 2...');
// Perform a half-close
// We signal completion of our send, but keep the socket open
client.end('Final data chunk.');
});
// The server can still send data back to us here!
client.on('data', (data) => {
console.log('Received response:', data.toString());
});
Why use this?
This pattern is essential for protocols where the client needs to send a request body of unknown size or multiple segments and then wait for a server response. By using end(), you clearly delineate the end of your transmission without prematurely killing the socket, allowing the server to process your complete input before sending a reply.
Key Takeaway: The socket half-close pattern allows you to signify the end of your outbound stream via socket.end() while maintaining the connection to receive the remaining inbound data.