问题
I have written android app which connects to a websocket server, server app and android app implemented with Autobahn websocket library.
I can connect and exchange the messages with server successfully. but after some time(after 20 - 30 mins) android app stop communicating with server(it cannot send messages to server). On logcat shows app still connect to websocket even though it cannot send messages to server.
I have went through the source code of Autobahn library and found that it using java.nio.channels.SocketChannel to connect to the websocket. Are there any issue in using SocketChannels? (I found similar issue from here Android - How to keep connection with server for a long time)
回答1:
Finally I have solved the problem by using webscoket ping/pong message.
Actually the problem is not with the SocketChannel, I have tried with plain Socket instead of using SocketChannel. Problem not solved even with the Socket.
This is the approach that I have used...
In order to keep websocket connection alive we need to use Ping/Pong messages that built in support from websockt protocol(more information websocket protocol ). Server need to send ping message in periodic time to clients. When ping receives from server, client replies it with pong message. Using this way we can keep the connection alive for ling time.
The Autobahn library that I have used to build my webscoket client support to this ping/pong messages. When ping message receives via websocket, library automatically send pong message to server. So we no need to worry about manually sending pong messages. You can find the autobahn implementation of ping/pong message from here (in createHandler() method - autobahn ping/pong implementation)
You can get more details about this topic from this thread as well Websockets. Loss of internet, keep-alive messages, app architecture etc
来源:https://stackoverflow.com/questions/21553208/connecting-to-websocket-using-socketchannel-android