Android - How to keep connection with server for a long time

天涯浪子 提交于 2019-12-24 02:15:02

问题


I wrote a chat application for Android using SocketChannel. It connects successfully with the server and all features work. But after a long time since I logged in (about 2-3 hours), I try to send a chat message again and it fails. In log file, SocketChannel, selector still open and connect to server, message already write successful. What's the problem? What am I missing?

Thanks in advance for your help.


回答1:


if you want to create a Chat for android or something else with push from a server, try it with MQTT

http://tokudu.com/2010/how-to-implement-push-notifications-for-android/

its is a very cool thing, just take a look at it :-)




回答2:


I have had a same kind of problem with SocketChannel. I have used SocketChannel based library to connect to a websocket from andoird application (The library is Autobahn websocket). I can successfully connect to web socket and can send/receives messages through the websocket. But After sometime(may be after 30 mins, 1 or 2 hours) the the websocket connection hangs. As your scenario, logs seems socket connection is still open and connect to server, message already write successful. But server won't receives the messages.

In my scenario problme is not with the SocketChannel. Problem is with TCP time out. In order to keep the connection alive I'm sending peroidic ping message from server to client. Web socket default support this messages call PING/PONG messages. This ping message need to be send to clients in periodic time, in order to keep the connection alive. When ping message receives client automatically replies PONG message to server. By using this approach I was able to keep the socket connection for a long time.

More information about this approach Solution for websocket hanging, Websockets. Loss of internet, keep-alive messages, app architecture etc, websocket protocol and ping/pong messages

Hope this would help to you(even though you are not using websocket). The approach could be same in websocket as well as your chat application.



来源:https://stackoverflow.com/questions/9859744/android-how-to-keep-connection-with-server-for-a-long-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!