In Embedded Linux, Java Socket quickly judges remote network disconnection

Source: Internet
Author: User

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!
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.