Java Timer.cancel() 不取消计时器

问题描述

我有一个用 Java 设置的简单套接字服务器和客户端。我想实现一种检查连接超时的方法。基本上,客户端每 5 秒向服务器发送一次 01101011 01100101 01100101 01110000。然后服务器检查它是否已经与从它接收到字符串的客户端建立了连接。

如果没有,则将客户端的 IP 添加到名为 connections 的数组中,并启动 30 秒计时器。如果 30 秒计时器到达终点,它将从 connections 数组中删除客户端。

否则,如果它已经与客户端建立了连接,那么它会取消 30 秒计时器并重新启动它。

这是我的代码:

//This if statement fires every 5 seconds when it received the string from the client
if(o.equals("01101011 01100101 01100101 01110000")) {
    Timer timeoutTimer = new Timer();

    if(Arrays.asList(connections).contains(connection.getOtherEnd().getAddress())) {
        timeoutTimer.cancel();
        timeoutTimer.purge();
        timeoutTimer = new Timer();
    }
    else {
        connections = ArrayModification.append(connections,connection.getOtherEnd().getAddress());
        System.out.println("Client connected");
    }
    timeoutTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            connections = ArrayModification.remove(connections,connection.getOtherEnd().getAddress());
            System.out.println("Client disconnected");
        }
    },30000);
}

它可以正常工作大约 30 秒,但是由于某种原因,它执行了应该被取消的计时器任务。

这是我的输出:

Client connected <- Happens when the client first connects
Client disconnected <- Happens 30 seconds later from the timer task that should've been cancelled
Client connected
Client disconnected
Client connected
Client disconnected
Client connected

我不明白为什么取消的计时器仍在运行。任何帮助将不胜感激!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)