The socket has already been ended.
Production Risk
Medium. This indicates a state management issue in handling network connections. It can lead to unhandled exceptions and crashes if not properly caught, although it often just signals a failed write.
This error is thrown when an attempt is made to write data to a socket that has already been closed. Sockets can be ended by either the local side calling `.end()` or the remote side closing its connection. Once a socket is in the ended state, no more data can be sent through it.
- 1Calling `socket.write()` or `socket.end()` after the socket has already been closed.
- 2A race condition where one part of the code closes a socket while another part is still attempting to write to it.
- 3The remote client disconnects, and the server code does not properly handle the 'close' event before trying to send more data.
This error occurs within the `net` or `http` modules when a write operation is initiated on a socket object that has already transitioned to a closed or ended state.
const net = require('net');
const server = net.createServer((socket) => {
socket.end('Goodbye!');
try {
socket.write('One more thing...'); // Throws error
} catch (err) {
console.error(err.code);
}
});
server.listen(3000);expected output
ERR_SOCKET_ALREADY_ENDED
Fix
Check if Socket is Writable
WHEN Before writing data to a socket in a long-lived connection.
function writeToSocket(socket, data) {
if (socket.writable) {
socket.write(data);
} else {
console.log('Socket is not writable, cannot send data.');
}
}Why this works
Before attempting to write, check the `socket.writable` property. If it is `false`, the socket has been closed or is in the process of closing, and you should not attempt to write to it.
const net = require('net');
const server = net.createServer((socket) => {
socket.end('Goodbye!');
try {
socket.write('One more thing...'); // Throws error
} catch (err) { // this triggers ERR_SOCKET_ALREADY_ENDEDtry {
// operation that may throw ERR_SOCKET_ALREADY_ENDED
riskyOperation()
} catch (err) {
if (err.code === 'ERR_SOCKET_ALREADY_ENDED') {
console.error('ERR_SOCKET_ALREADY_ENDED:', err.message)
} else {
throw err
}
}function safeSend(socket, data) {
if (socket.writable) {
socket.write(data)
}
}✕
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev