java检查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 (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 用于文本。你不需要它们,它们会增加困惑。

要检测服务器已消失,您需要发送一段数据并获得响应。如果您在一定时间内不这样做,连接或服务就会丢失。

关于java检查tcp套接字是否还活着?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18584474/

相关文章:

java - OS X El Capitan 上的 Eclipse 错误 : Could not find or load main class

java - java中重命名文件的最佳方法,目录中大约有500个文件

Linux Socket编程 : what happen in server socket when client socket gone off in the middle of communication

silverlight - 如何从 SilverLight 打开 TCP 套接字?

java - 当用户按下 JButton 时,如何将 JTable 中的特定行设为 "go to"?

java - 虚函数和纯虚函数有什么区别?

ios - 如何向大量iPhone发送少量数据

actionscript-3 - 在 Flash 中发送 XML 和接收响应的最佳类设计

php - 如果尚未接受套接字,则主套接字是否仍可以使用socket_select-?

android - TCP 客户端/服务器与多播广播