📄 e180. detecting when a non-blocking socket is closed by the remote host.txt
字号:
The only way to detect that the remote host has closed the connection is to attempt to read or write from the connection. If the remote host properly closed the connection, read() will return -1. If the connection was not terminated normally, read() and write() will throw an exception.
When using a selector to process events from a non-blocking socket, the selector will try to return an OP_READ or OP_WRITE event if the remote host has closed the socket.
try {
// Read from socket
int numBytesRead = socketChannel.read(buf);
if (numBytesRead == -1) {
// No more bytes can be read from the channel
socketChannel.close();
} else {
// Read the bytes from the buffer
}
} catch (IOException e) {
// Connection may have been closed
}
try {
// Write to socket
int numBytesWritten = socketChannel.write(buf);
} catch (IOException e) {
// Connection may have been closed
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -