1

This is the link to my code. On service start a socket a created that sends data to the server from android client. This service is stopped on destroy.

But I noticed, if my client loses connection with the server I have no way of knowing it and worse I cannot reconnect to the server.

I assume the best way would be to receive an echo of the command sent by the client to the server and if there is no reply from server understand that the connection is lost. After knowing that the connection is lost I need to self stop the service and restart it. I have no idea how to go about it. After doing this I need to rebind to the activity.

The other way is the client socket should be opened and closed for every data being sent. This way it automatically reconnects to the server. I do not know how to do this too.

Any help is appreciated

Community
  • 1
  • 1
gfernandes
  • 1,156
  • 3
  • 12
  • 29

2 Answers2

2

I have modified my code to implement the second solution suggested in the question. Instead of creating a socket on startservice(), I now create it and close it everytime the client wants to send data. This way I do not have to stop my service on connection loss. The Server side I modified to be indefinitely listening to the port unless indicated by the client to break out of the loop and disconnect.

public void sendMessage(String message){
      //making message variable global to the SocketSevice class
      this.message=message;

      //connecting to class that performs socket connection
      Runnable connect = new connectSocket();
      new Thread(connect).start();

    }
gfernandes
  • 1,156
  • 3
  • 12
  • 29
0

When you want to restart your service just send a broadcast message to one of your activity. on receiving your broadcast message write a piece of code to start the service on the activity which your broadcast receiver is defined. (kill the service inside of service class or on the broadcast receiver class)

Jai Kumar
  • 920
  • 1
  • 7
  • 14
  • ok. That is a good idea, but the problem is I have multiple activities and I would not know when the connection is lost which activity is running. So I will have to implement the broadcast receiver for all activities? – gfernandes Mar 14 '13 at 10:26
  • No.. when a connection is lost just send a broadcast.. you may use separate broadcast receiver class. from that broadcast receiver class you again start your service.. – Jai Kumar Mar 15 '13 at 05:59