?? 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 + -