java检查tcp socket是否还活着?

时间:2013-09-03 05:08:54

标签: java sockets tcp

我使用以下代码从服务器读取消息:

   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();
               }
           }
       }
   }

如何检测连接是否下降?例如,如果服务器崩溃了?

1 个答案:

答案 0 :(得分:1)

请不要将DataInputStream或DataOutputStream用于文本。你不需要它们,它们会增加混乱。

要检测服务器已经消失,您需要发送一段数据并获得响应。如果您没有特定时间,则连接或服务将丢失。