java - 在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);
}
解决方案
推荐阅读
- cassandra - 在 Cassandra 中,为什么不允许从使用紧凑存储定义的表中删除列?
- xpages - 生成要与 Wowza CDN Cloud 一起使用的身份验证令牌
- amazon-web-services - “$path”是否限制 Athena 扫描的数据量?
- node.js - 在同一个父文档中加入 MongoDB 子文档
- xml - xmllint 没有返回我所期望的——n00b 警告
- reactjs - ReactJS:在我的情况下如何正确管理状态
- r - 在 R 中,有没有办法改变数据的结构,使标识符是列标题?
- typescript - 如何在打字稿中创建枚举值作为类型/接口?
- javascript - 计算 JS 数组中重复的 Date() 对象
- node.js - 这是什么意思 SyntaxError: 不能在模块外使用 import 语句?