JAVA ANDROID Socket Communication Detection (SERVER) connection is disconnected

Source: Internet
Author: User

    • Pre
    • Solution Ideas
    • Code PostScript:
      • Part of the code on the client app
      • Call:
      • On the server:
      • The client determines if the server is still alive code:
PRE

When using the socket to write the communication program, want to detect whether the server is still alive.

From the Internet to find a lot of information, none of their own suitable, and finally think of a way, but also quite a part of the heartbeat detection.

This detects the connection to the remote server, not whether the connection is successful locally. First think of the socket class method isClosed()、isConnected()、isInputStreamShutdown()、isOutputStreamShutdown() , but after testing and review the relevant documents, these methods are local side state, cannot determine whether the remote is disconnected.

And there is a way sendUrgentData to look at the document and know that it will send a byte of data to the output stream, as long as the So_oobinline property of the other socket is not open, it will automatically discard this byte.

Or, in fact, if you disconnect, you send the past data will not receive, the last client will throw an IO exception.

However, the above two methods throw an exception for up to 15 seconds! I can't bear it.

Solution Ideas

Of course, the demand environment here is: the number of data sent is very small, almost only need to judge one or two times, the data is sent centrally. Well, that's the way to go:

As long as the client sends a custom test data before sending the data, and customizes a variable such as a string (initial value null) to receive the data sent back by the server, the client sends out the test data, sleeps 500 milliseconds (custom time) (asynchronously receives the server message), Then immediately detect if the string is null, and you can tell if the server is receiving a message.

Codepart of the code on the client app
/** client thread, used to establish a connection and send a message */PublicClassClientImplementsrunnable{Socket s=Null DataInputStream dis=Null DataOutputStream dos=NullPrivateBoolean isconnected=False Thread receivemessage=Null/** Send Message *@param str sends the message, the client only sends two messages to the server, which is my own application needs, according to the actual situation to do yours. *@throws IOException * * * *PublicvoidSendMessage (String str)Throws ioexception{Dos.writeutf (str); Dos.flush ();}/** Disconnect */PublicvoidDisConnect () {try {dos.close (); Dis.close (); S.close ();}catch (IOException e) {System.out.println ("Client closed error"); E.printstacktrace (); } }/** set up a socket connection, open the receive data thread * */PublicvoidRun () {try {s=New Socket (Server_host_ip,server_host_port); S.setoobinline (true); dis=New DataInputStream (S.getinputstream ()); dos=New DataOutputStream (S.getoutputstream ()); System.out.println ("connected!"); Isconnected=True Receivemessage=New Thread (New Receivelistenerthread ()); Receivemessage.start ();Send Imei sendMessage (IMEI); }catch (Unknownhostexception e) {System.out.println ("Fuwuqoweikaiqi"); E.printstacktrace (); }catch (IOException e) {System.out.println ("Ioerr"); E.printstacktrace (); } }PrivateClassReceivelistenerthreadImplementsrunnable{This section receives data processing, please modify the String according to the actual situation data[]=New string[3];Publicvoid run () {try {if (isconnected) {String receivedmessage=dis.readutf (); System.out.println (Receivedmessage); Serverstarted=true; Data=receivedmessage.split ( "_"); Islegal=integer.parseint (Data[0]); Num1=integer.parseint (data[ 1]); Num2=integer.parseint (Data[2]); System.out.println ( "+islegal+num1+" +num2);} if (isconnected) {Finalok=dis.readutf ();}} catch (socketexception e) {System.out.println ( "exit!"); Span class= "Hljs-keyword" >catch (IOException e) {e.printstacktrace ();}} }
Call:
Client client=null;/**客户端网络线程*/Thread tClient=null;client=new Client();tClient=new Thread(client);tClient.start();
on the server:
/** This is the thread class that the server uses to receive processing clients */class client implements Runnable {Private Socket S;Private DataInputStream dis =NullPrivate DataOutputStream dos =NullPrivateBoolean isconnected =FalsePublicClient (Socket s) {THIS.S = s;try {dis =New DataInputStream (S.getinputstream ()); DOS =New DataOutputStream (S.getoutputstream ()); isconnected =True }catch (IOException e) {System.out.println ("On clients ' data in and out has the error");E.printstacktrace (); } }PublicvoidRun () {String str;try {Check whether a legitimate client is the firstwhile (isconnected) {str = DIS.READUTF (); str = Dis.readutf ();//The specific code here omits Dos.writeutf ("OK"); Dos.flush ();}} } catch (Eofexception e) {System.out.println ("Client closed"); Home.appendmessage ((Legalnum + 1) + "Client has logged out"); catch (IOException e) {e.printstacktrace ();} finally { try { if (dis! = null) dis.close (); if (dos = null) dos.close (); if (s! = null) s.close ();} catch (IOException e) {e.printstacktrace ();}} } }
the client determines if the server is still alive code:
try {The client sends a test message client.sendmessage (cookie); System.Out.println ("Send");//sleeps 1 seconds systemclock.sleep (1000); //this finalok is handled at the client's receiving thread. If not null the server is OK if (Finalok!=null) {client.disconnect (); Exit ( "Thank you for your use, this time has ended ~");} else{throw new IOException (); Span class= "hljs-comment" >//Timeout detection} catch (IOException e) {new Alertdialog.builder (Mainactivity. This). Settitle ( "hint"). Setpositivebutton ( "good", null". Setmessage ( "The server is down, please contact the administrator and click" Send "again after the server is turned on to submit the data"). Show (); Client.disconnect (); E.printstacktrace (); } 
PostScript:

Originally just a simple record of their own ideas, writing is very humble, did not think slowly this article is still a lot of people to see, deeply disturbed, so update to add a bit.

2015.3.27

statement:
article if no description reproduced, are original, if you need to reprint, please indicate the source!

JAVA ANDROID Socket Communication Detection (SERVER) connection is disconnected

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.