I'm currently developping an Android application which connects to a server through TCP. The server is written in Qt and runs on a computer.
In server side, I use a QTcpServer
and the signal QTcpServer::newConnection()
to get the QTcpSocket
newly connected with QTcpServer::nextPendingConnection()
. I have implemented a class I called SocketManager
, which manages the data received by this socket.
In Android side, I use java Socket to connect to the server.
All work great. When the Android side disconnects from the server, my SocketManager
object is well notified and destroys 开发者_开发知识库itself. But I would like to manage properly the case when for example the Android device goes to offline or is turned off. In that case, I'm not notified of the disconnection of Android. I connect these signals of my QTcpSocket
:
QAbstractSocket::disconnected()
,QAbstractSocket::stateChanged(QAbstractSocket::SocketState)
QAbstractSocket::error(QAbstractSocket::SocketError)
QObject::destroyed(QObject*)
, thinking that perhaps the QTcpSocket is internally destroyed by the QTcpServer.
But no signal is received when the Android device goes offline or is turned off.
When the QTcpSocket will be released by the QTcpServer
? Only when the socket is explicitely disconnected? So in my case, will it never be destroyed? Should I manage the disconnection in all cases in the Android side?
Thanks everyone.
TCP will not notify you of disconnections unless the remote peer explicitly sends disconnect request (by using close() or shutdown() methods) or you try to write to a disconnected socket (in which case you get a broken pipe signal)
The classical way to solve this problem is implementing a heartbeat messaging system where after a certain amount of heartbeat inactivity you close the socket concluding that the remote peer has died suddenly or there is a network problem.
精彩评论