首页 > 解决方案 > 在Java多线程中停止特定IP地址的套接字线程

问题描述

我正在设置一个服务器软件来接受来自 ESP32 板的多个连接。在测试过程中,服务器能够在100ms内接收多个连接和多个消息而不会卡住。但是,现在的问题是服务器无法检测到与 ESP32 的离线断开连接。我需要停止特定线程以停止连接,因为当板断开连接时,它会尝试再次重新连接。为新连接打开了一个新线程,但旧线程仍在运行。

连接的客户端将列在服务器端的 JTable 中。我曾尝试使用 Thread.interrup() 但它不起作用,因为代码等待从客户端接收某些内容以开始连接。

下面是删除相同 IP 地址以避免冗余连接的代码,因为我正在使用修复 IP 地址和中断线程。由于断开连接,如何停止正在运行的删除 IP 地址的线程?为了获得成功的中断线程,我需要在 run() 中停止 readLine() 吗?下面是 ClientHandler 和 run() 中的代码片段,它将等待来自客户端的数据/消息进行连接。

socket = clientSocket;

    //Get client IP Address
      clientIP = socket.getInetAddress().getHostAddress();

      Socket socket1;               
      for(int i = 0; i < clientSockets.size(); i++) {
        socket1 = clientSockets.get(i);
                    if(socket1.getInetAddress().getHostAddress().equals(clientIP)) {
                tableModel.removeRow(i);
                    clientSockets.remove(socket1);
                    JTextArea.append(clientIP + " - Disconnected.");

                JTextArea.append("1. Before interrupt--------");
            for(Thread t : Thread.getAllStackTraces().keySet()) 
               {
            JTextArea.append(t.getName());
            }
        JTextArea.append("--------");


        for(Thread t : Thread.getAllStackTraces().keySet()) 
        {
          if(t.getId() == threads.get(i).getId()) 
           {
            threads.remove(i);
                t.interrupt();
            break;
              }
           }

        JTextArea.append("2. After interrupt--------");
        for(Thread t : Thread.getAllStackTraces().keySet()) 
        {
           JTextArea.append(t.getName());
        }
           JTextArea.append("--------");
     }
}


run(){
while ((message = netin.readLine())!=null)// Need to stop the readLine() here to interrupt the thread if not cannot stop it.
try {                   

     String[] data = message.split("&");

      Vector<Object> tableRow = new Vector<Object>();

      if(data[0].equals("connection")) {
      msg1= data[1];
      msg2= data[2];
      msg3= data[3];

      tableRow.add(clientIPAddress);
      tableRow.add(msg1);
      tableRow.add(msg2);
      tableRow.add(msg3);
      // Add a client row into the table
      tableModel.addRow(tableRow);
}
       JTextArea.append("Stop Thread.");

      } catch (Exception ex) {
      JTextArea.append("Run Exception:" + Thread.currentThread().getId() + "-" + ex);
}

标签: javamultithreadingsocketsserversocket

解决方案


推荐阅读