简体   繁体   中英

Java on Android - Strange socket behavior with InputStream timeout errors

I have an app which uses an instance of the Socket class to communicate with a server. I use the streams returned by socket.getInputStream() and socket.getOutputStream() to read and write data.

When my Android app is always "active" (not minimized), there is no problem with the communication. It does not matter how long the connection lasts.

When I "pause" the application and re-open it quickly, everything still works fine. However, when I pause the application for about 5 minutes and re-open it, the InputStream shows strange behavior: it stops reading anything. I get timeout errors instead of the data sent by the server.

The connection is still alive, the server is able to write and read. isInputShutdown() on the client-side returns false.

Using a network analysis tool, I can also see that the data sent by the server IN FACT reaches the client but it somehow does not get recognized by the InputStream ...

However, writing data from the client to the server using the OutputStream works fine.

Maybe it's worth mentioning that the socket object and the streams are declared as static to be accessible for all the activities of the app. But as I don't have any problems with the OutputStream , I cannot imagine that this could be the reason.

The only workaround I have at this point is to close the whole socket and connect a new one to the server. But this is causing unnecessary network traffic because I have to handshake again. It would be better not to do it this way.

If anyone has had similar experience and found a solution, I would be really happy if you could share it with me.

您应该创建将在后台运行的服务,并实现与服务器的套接字连接。

As Kevin Krumwiede pointed out by referring to this post: Strange behavior of socket outputstream android , when sending data every X minutes (eg 3 or 4), everything still works as it should even after 30 minutes of being 'paused'.

I had the hope that Socket.setKeepAlive(true) would be enough to keep the connection alive so I dont have to cause too much unnecessary network traffic but in my particular case, this does not help.

Sending 1 byte of 'garbage' every X minutes 'solves' the problem.

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