Reputation: 865
I have a server
program in python
which sends and receives data packets
to and from android client
. I am using TCP
with sockets
in android client
to communicate with python
program.
Every thing is working fine but when the server
is shutdown with an NSF power failure it disconnected from client
.
My Question is how I check for the availability of the server all the time using android
services or any BroadcastReceiver
or inside my MainActivity
when socket
closed or disconnected.
I don't want to restart my client application
again after server
power failure.
Upvotes: 2
Views: 887
Reputation: 865
For those with the same issue.
I have created AsyncTask
to ping
or heartbeat
the server
and call this task every second using Timer
in my MainActivity
.
new Timer().schedule(new TimerTask(){
@Override
public void run(){
new connectTaskMain().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}, 1000);
Upvotes: 0
Reputation: 104514
In the absence of data being exchanged and without the TCP keep-alive option set on the socket, a socket will be unaware that the remote connection suddenly disappeared. This isn't anything new, it's been a well known socket design problem.
The general pattern is to have some sort of keep alive or ping protocol on the socket that sends a "I'm still here" message between client and server so both endpoints know the other side hasn't gone away. When an endpoint goes offline, the remote socket will fail on a subsequent recv\send call (or throw an exception). Thereby the application or server can handle the disconnect as it sees fit. But this presents an interesting challenge on mobile - frequent network messages may drain the battery by keeping the radio on.
Mobile devices, including Android, typically don't keep long running socket connections to services. Instead, the client will "connect on demand" and close the socket when it's done. Similarly, if the server needs to send something to the device, it typically makes use of the platform's "push" notification service. On Android, the current push notification service is FCM. The client registers with FCM and the server. When the server has something new to give to the client, it sends a push notification through FCM. The client app in turn, gets the notification message as a wakeup that something new is available, and then reconnects to the server to get the actual message. The best example of this is email on a mobile device.
Upvotes: 1