Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java检查tcp套接字是否处于活动状态?_Java_Sockets_Tcp - Fatal编程技术网

java检查tcp套接字是否处于活动状态?

java检查tcp套接字是否处于活动状态?,java,sockets,tcp,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 (IOExce

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

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

如何检测连接是否断开?例如,如果服务器崩溃,请不要将DataInputStream或DataOutputStream用于文本。你不需要它们,它们会增加混乱


要检测到服务器已关闭,您需要发送一段数据并获得响应。如果您在特定时间内没有联系,连接或服务将丢失。

我将把这段数据发送到哪里?在计时器内的我的线程中?@Alosyius假设您的协议允许写入服务器将响应的消息,您可以在另一个线程中发送该消息,并在没有及时读取数据的情况下让它关闭连接。