简体   繁体   中英

How to catch broken pipe for sockets?

I have written a Java client-server application using Sockets. I'm using the method writeUnshared() of ObjectOutputStream and readObject() of ObjectInputStream .

Now I would like to detect when the connection is broken to reconnnect (eg when Wifi signal was lost). Currently, for ObjectInputStream I'm catching EOFException and for ObjectOutputStream I'm catching IOException to detect if the pipe is borken.

Is this correct or should I catch IOException for both streams?

You can go by the Javadoc , which recommends catching IOException for all of the usual I/O related exceptions.

Or you can go by your own testing.

Or you can go by the source code , which shows that when using "block data" mode EOFException is used by serialization whenever there is insufficient bytes to construct a full object. However, that would not catch all cases in which the connection is broken.

All things considered, I would recommend IOException.

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