First, we will introduce my platform and application environment. The hardware platform I use is the friendly arm Micro2440, the software platform is Embedded Linux, and the kernel version is 2.6.32, using the java language.
You may know that when using Java Socket programming, it is often necessary to check whether the network is connected properly. For example, the Socket server checks whether the connection with the client is disconnected. First, consider the socket class methods, such as isClosed (), isConnected (), isInputStreamShutdown (), and isOutputStreamShutdown (). However, after testing and viewing relevant documents, these methods are all local statuses, you cannot determine whether the remote connection is disconnected. When using the Socket isconnected () method for detection, the latency is very large, usually more than 20 seconds. This is not conducive to the real-time performance of the system.
Then you can determine whether you can send a piece of test data through OutputStream. If the sending fails, the remote end is disconnected, similar to ping, but this will affect normal output data, the remote end cannot separate normal data from test data. We found that there is a method sendUrgentData. After reading the document, we know that it will send a byte of data to the output stream. As long as the SO_OOBINLINE attribute of the Socket of the other party is not opened, this Byte will be automatically discarded, the SO_OOBINLINE attribute is disabled by default.
The code used is as follows:
Public boolean isConnected (){
Try {
S. sendUrgentData (0xFF );
Return true;
} Catch (Exception e ){
Return false;
}
}
Tests show that the system can quickly detect the network status!