Skip to content

Instantly share code, notes, and snippets.

@wermarter
Created September 24, 2024 04:46
Show Gist options
  • Select an option

  • Save wermarter/d914f4918a2403208d63f3a1f1c4b2b1 to your computer and use it in GitHub Desktop.

Select an option

Save wermarter/d914f4918a2403208d63f3a1f1c4b2b1 to your computer and use it in GitHub Desktop.
NodeJS TCP half-close
const net = require('net')
const server = net.createServer({ allowHalfOpen: true }, (socket) => {
socket.on('data', (data) => {
console.log('Server <-', data.toString())
if (!socket.writableFinished) {
socket.write('hello')
console.log('Server -> hello')
// half-close
socket.end()
console.log('Server -> FIN')
}
})
socket.on('end', () => {
console.log('Server <- FIN -> ACK')
if (!socket.writableFinished) {
socket.write('afterword')
console.log('Server -> afterword')
socket.end()
}
})
})
server.listen(8080, () => {
console.log('Server listening on port 8080')
})
// ----------------------------------------------------
const client = net.createConnection({ port: 8080, allowHalfOpen: true }, () => {
client.write('hello')
console.log('Client -> hello')
// half-close
// client.end()
// console.log('Client -> FIN')
})
client.on('data', (data) => {
console.log('Client <-', data.toString())
})
client.on('end', () => {
console.log('Client <- FIN -> ACK')
if (!client.writableEnded) {
client.write('afterword')
console.log('Client -> afterword')
client.end()
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment