JAVA determines whether the socket remote side is disconnected

Source: Internet
Author: User

Recently in the project, encountered such a problem, how to determine whether the socket remote connection is closed, if it is closed, it is necessary to rebuild the connection socket class provides some methods that have been encapsulated, such as isClosed (),isconnected (), Isinputstreamshutdown (), Isoutputstreamshutdown () , etc., were found in the test, these methods are local state , cannot determine whether the remote is disconnected.

In fact, there is a method in the socket class Sendurgentdata, 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 (in Java is thrown exception), The So_oobinline property is turned off by default.

The following is a sample code for reference only:

public class Nksocket extends thread{public String ip=null;//connect the server's IP public Integer port=null;//the port of the connection server private Sock Et socket=null;//the private Boolean close = False for the nested-word object; Close the connection flag bit, true to close, false to connect the private Integer sotimeout=1*1*10;//time-out, in milliseconds//------------------------------------  ------------------------------------------public Nksocket () {init ();     } public Nksocket (String Ip,integer port) {setIp (IP);     Setport (port);  Init ();      }/** * Initialize the Socket object */public void init () {try {inetaddress address = Inetaddress.getbyname (GetIP ());      Socket = new Socket (Address,getport ()); Socket.setkeepalive (TRUE);//Turn on the active socket Socket.setsotimeout (sotimeout);//Set timeout time close=!     Send (Socket, "2");//Transmit initial data, send success indicates already connected, send failure indicates that}catch (Unknownhostexception e) {e.printstacktrace () has been disconnected;     }catch (IOException e) {e.printstacktrace ();  }}/** * Read data thread */public void run () {while (true) {///---------Read Data---------------------------    Close = isserverclose (socket);//Determine if disconnect if (!close) {//Do not break, start reading data String readtext = READTEXT (socket);       if (Readtext!=null && Readtext.trim (). Length () >0) {System.out.println ("read data:" +readtext); }}//---------Create connection-------------------------while (close) {///has been disconnected, reestablish connection try{System.out.printl        N ("Re-Establish Connection:" +getip () + ":" +getport ());        InetAddress address = Inetaddress.getbyname (GetIP ());        Socket = new Socket (Address,getport ());        Socket.setkeepalive (TRUE);        Socket.setsotimeout (SoTimeout); Close =!        Send (Socket, "2");       SYSTEM.OUT.PRINTLN ("Establish connection succeeded:" +getip () + ":" +getport ());        }catch (Exception se) {System.out.println ("Create Connection failed:" +getip () + ":" +getport ());       Close=true; }}}}/** * Send data, send failed to return false, send successful return true * @param csocket * @param message * @return */public Boolean Send (S Ocket csocket,string message) {try{PrintWriter out = new PrintWriter (Socket.getoutputstreaM (), true);      OUT.PRINTLN (message);     return true;      }catch (Exception se) {se.printstacktrace ();     return false; }}/** * read data, return string type * @param csocket * @return * * * public String ReadText (Socket csocket) {try{csocket.sets      Otimeout (SoTimeout);      InputStream input = Csocket.getinputstream ();      BufferedReader in = new BufferedReader (new InputStreamReader (input));      char[] sn = new char[1000];      In.read (SN);      String sc = new string (SN);     return SC;     }catch (IOException se) {return null;   }}/** * Determines whether to disconnect, returns true without returning false * @param socket * @return */Public Boolean Isserverclose (socket socket) {try{socket.sendurgentdata (0xFF);//send 1 bytes of emergency data, by default, the server side does not open the emergency number     According to the processing, does not affect the normal communication return false;     }catch (Exception se) {return true; }  }/** * Test * @param AGS */public static void Main (string[] AGS) {nksocket nksocket = new Nksocket ("127.0.0.1", 8090);  Nksocket.start (); }//------------------------------------------------------------------------------public String GetIP () {return IP  ;  } public void SetIp (String IP) {this.ip = IP;  } public Integer Getport () {return port;  } public void Setport (Integer port) {this.port = port; }  }

  

Resources:

http://blog.csdn.net/xyz_lmn/article/details/6146749

http://ivan4126.blog.163.com/blog/static/20949109220135284278806/

JAVA determines whether the socket remote side 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.