0

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

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

如何检测连接是否断开?例如,如果服务器崩溃?

4

1 回答 1

1

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

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

于 2013-09-03T05:19:49.517 回答