简体   繁体   中英

java check if tcp socket is alive?

I am using the following code to read messages from a server:

   Socket socket;
   try {
       socket = new Socket(InetAddress.getByName("url.com"), 8080);
       is = new DataInputStream(socket.getInputStream());
       os = new DataOutputStream(socket.getOutputStream());
   } catch (IOException ex) {
       Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);


       JOptionPane.showMessageDialog(rootPane,
           "Could not establish network connection to the server." + " \nPlease check your internet connection and restart the application.",
           "Unable to connect",
           JOptionPane.INFORMATION_MESSAGE);

       WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
       Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);
       setVisible(false);
       dispose();
       System.exit(0);
   }

    // Start thread to listen for messages from the server
   new ListenFromServer().start();


   /*
    * Thread class to listen for message from the server
    */
   class ListenFromServer extends Thread {

       public void run() {
           BufferedReader in = new BufferedReader(new InputStreamReader(is));

           while (true) {

               try {

                   String tmpMsg = in .readLine().replaceAll("\\r\\n|\\r|\\n", "");

                   JSONObject json = new JSONObject(tmpMsg);

                   if (json.get("type").toString().contains("preview")) {
                       System.out.println("PREVIEW: " + json.get("msg").toString());



                   }


               } catch (Exception e) {
                   e.printStackTrace();
               }
           }
       }
   }

How can i detect if the connection drops? For example if the server crashes?

Please do not use DataInputStream or DataOutputStream for text. You don't need them and they add confusion.

To detect a server has gone you need to send a piece of data and get a response. If you don't with a certain time, the connection or service is lost.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM