简体   繁体   中英

Java Sockets - Detect network disconnect without inputstream

I've recently been writing java code to send notifications to the Apple Push Notification server. The problem I'm running into is if I create the socket and then disconnect from the network. I've bounced around articles on-line and most suggest relying on the methods:

socket.setKeepAlive(false);
socket.setSoTimeout(1000);

Specifically the "setSoTimeout" method. But the javadoc states that setSoTimeout will only throw an exception when reading from the InputStream. But the Apple Push Notification server never puts any data on the InputStream so I can never read anything from it. Does anyone have any suggestions of how to determine a network disconnect without using the socket InputStream?

You can only reliably detect a Socket has been disconnect when you attempt to write or read from a Socket. Reading is better because writing often takes a while to detect a failure.

The server doesn't need to write anything for you to attempt to read it. If you have a server which never writes you will either read nothing or detect a failure.

A quick precision: APNS will return data on your InputStream if you are using the enhanced notification format and that some error occurs. You should therefore make sure you do not ignore your InputStream...

Unless you are doing this as a personal learning project, you might want to take a look at existing APNS-specific Java libraries that deal with all the communication details for you. Communicating reliably with APNS is much more difficult than it looks at first, especially when you get to the error management part which involves various vague or undocumented details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM