It's been a whole day studying the problem today! Finally came out, but I do not have much sense of accomplishment, why? Because this is the work of my seniors. The same problem, I did not want to come out! The heart is stuffed very well ...
But still want to share with you, hope to bring you help!
First declare: Not I do not put the source, is because this feature is a small part of my project, paste the source is too powerful, and can not be used after downloading, so stick to the core code ~
I send a heartbeat to the server every minute to keep the connection, as follows:
The code in SendObject () (that is, sending the content to the server):
Public void throws IOException { new DataOutputStream (Socket.getoutputstream ()); Os.write (Obj.getbytes ()); Os.flush (); System.out.println ("send:" + obj + "client"); }
The point is, how to ensure the service restart when the automatic connection?
Public Static voidResetsocket () { while(Socketclient.isserverclose (socket)) {Try{Socket=NewSocket (Serverip,port); } Catch(unknownhostexception e) {//TODO auto-generated Catch block//e.printstacktrace ();}Catch(IOException e) {System.out.println ("Being re-connected ...."); //TODO auto-generated Catch block//e.printstacktrace (); } } } /*** Determine if disconnect, break return True, no return false *@paramSocket *@return */ Public StaticBoolean isserverclose (socket socket) {Try{socket.sendurgentdata (0);//send 1 bytes of emergency data, by default, the server side does not open the emergency data processing, does not affect the normal communication return false; }Catch(Exception se) {return true; } }
Finally, the Socketclient.resetsocket () will be placed in the image catch{}, when the exception is caught reconnect, you can achieve the desired effect.
Hope to bring you help, thank you!
The Android client automatically re-connects after the Android-socket service is restarted