After the Android-socket server is disconnected and restarted, the android client automatically reconnects to the androidsocket server.
I have been studying this issue for a whole day! I finally came out, but I didn't have much sense of accomplishment. Why? This is the result of my senior student's work. I did not think of the same problem! It's amazing ......
But I still want to share with you the hope to help you!
First, let me explain: I didn't leave the source code, because this function is a small part of my project. The source code is too powerful, and it may not be usable after download, so paste the core code ~
I send a heartbeat to the server every minute to maintain the connection, as shown below:
Code in sendObject () (that is, sending content to the server ):
Public void sendObject (String obj) throws IOException {DataOutputStream OS = new DataOutputStream (socket. getOutputStream (); OS. write (obj. getBytes (); OS. flush (); System. out. println ("Send:" + obj + "client ");}
The point is, how can we ensure automatic connection when the service is restarted?
Public static void resetSocket () {while (SocketClient. isServerClose (socket) {try {socket = new Socket (SERVERIP, PORT);} catch (UnknownHostException e) {// TODO Auto-generated catch block/e. printStackTrace ();} catch (IOException e) {System. out. println ("re-connecting .... "); // TODO Auto-generated catch block // e. printStackTrace () ;}}/ *** determines whether to disconnect. If yes, true is returned. If no value is returned, false * @ param socket * @ return */public static Boolean isServerClose (Socket socket) is returned) {try {socket. sendUrgentData (0); // sends 1-byte emergency data. By default, the server does not enable emergency data processing and does not affect normal communication. return false;} catch (Exception se) {return true ;}}
Finally, put SocketClient. resetSocket (); into the catch {} in the image, and reconnect when an exception is caught to achieve the desired effect.
Hope to help you. Thank you!