加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何以编程方式取消从InputStream读取?

发布时间:2020-12-15 08:43:34 所属栏目:Java 来源:网络整理
导读:我查看了StackOverflow和谷歌,但无法找到问题的解决方案,所以这就是我正在做的事情. 我有一个控制台应用程序的服务器,用户使用任何Telnet客户端连接到它.我正在处理具有三个独立线程的客户端,一个线程(ClientThread)控制对客户端的所有程序访问,ClientThread
我查看了StackOverflow和谷歌,但无法找到问题的解决方案,所以这就是我正在做的事情.

我有一个控制台应用程序的服务器,用户使用任何Telnet客户端连接到它.我正在处理具有三个独立线程的客户端,一个线程(ClientThread)控制对客户端的所有程序访问,ClientThread维护两个线程,一个用于处理输入,一个用于发送输出. ClienThread读取客户端套接字并将输入(如果有)发送到ProcessingThread,ProcessingThread处理输入并执行用户指定的操作.输出线程管理需要发送的输出队列,并在每次唤醒时发送它.当用户断开连接时我偶尔会在连接终止之前使用输出“队列”中剩下的输出,所以我想设置它以便连接保持活动直到输出队列为空 – 但是读取套接字的线程(并且当没有更多输出时最终关闭它)挂在读取上,我无法关闭它.在用户断开连接之前,我刚关闭了Socket,这不是问题.我会给你相关的代码.

public class ClientThread extends Thread {
   // Initialization and other code not pertaining to the problem 

   public void run() {
      while (connected) {
         try {
            String input = in.readLine();

            if (input != null) {
               processor.queue(TextUtility.processBackspaceChars(input));
               timeoutTimer.interrupt();
            }
         } catch (Exception e) {
            if (e.getMessage() != null && !(e.getMessage().equals("socket closed")))
               server.appendError("Issue reading from client: "
                     + getClientDisplayInfo() + "n"
                     + "&r-The issue is:&w- " + e.getMessage() + "&r-.");
         }
      }

      while (disconnecting) {
         try {
            if (outputThread.hasOutput()) {
               sleep(10);

            } else {
               disconnecting = false;
               outputThread.disconnect();
               client.close();
            }
         } catch (Exception exc) { 
            server.appendError("Failed to close the Thread for client: " + getClientDisplayInfo());
         }
      }  
   }   

   public void disconnect() {
      try {
         connected = false;
         disconnecting = true;
         processor.disconnect();
         timeoutTimer.disconnect();
         in.close(); // This is the BufferedReader that reads the Socket Input Stream
         this.interrupt(); // This was my attempt to break out of the read,but it failed

      } catch (Exception e) {
         server.appendError("Failed to close the Thread for client: " 
               + getClientDisplayInfo());
      }
   }
}

我只是好奇如何在不关闭Socket的情况下取消读取,因为我需要继续发送输出.

解决方法

我想它类似于我遇到的问题 yesterday您可以在输入流上调用is.available()并在执行(阻塞)读取之前检查数据是否可用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读