java util扫描仪超时?

时间:2012-07-11 17:59:41

标签: java java.util.scanner bufferedreader

我有以下问题,我的应用程序中有一个简单的TCP类,它将消息发送到设备进行查询,然后设备响应消息但是没有任何描述的行尾字符,因为它来自串行转换器,在最初试图使用readline函数并发现它需要eol字符输出之前我已经尝试了扫描仪功能工作正常,除非设备由于某种原因没有回复该请求,我的应用程序然后冻结,是否可以设置扫描仪功能的超时,以便它然后断开连接并继续前进或有更好的方法来执行此操作?我的代码如下:

public String Send_TCP ( InetAddress IPAddress, int POrt, String InData) throws IOException
         {      

        Socket socket = null;
        PrintWriter out = null;
        BufferedReader in = null;

        try {
            socket = new Socket(IPAddress, POrt);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection");
            System.exit(1);
        }

        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
        ;

        System.out.print("Connected, Sending:"+ InData);

        out.println(InData);
        System.out.println("Equals");
        String str1 = new Scanner(in).useDelimiter(">").next() + ">";
        System.out.println(str1);
        System.out.println("Equals");
        out.close();
        in.close();
        read.close();
        socket.close();
        return str1;
    }
}

2 个答案:

答案 0 :(得分:2)

我不确定我是否正确理解了您的问题,但您可以在套接字上设置超时:socket.setSoTimeout(int timeout)。 请参阅:javadoc

答案 1 :(得分:-1)

我相信以下内容实现了我所需要的,基本上检查缓冲区是否存在,如果它不存在则等待并再次检查以避免扫描器功能的陷阱如果消息永远不会到达,如果它读取它。 / p>

    try {
    BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream()));
    int count = 1;

        do { 
            if (rd.ready()){
                System.out.println ("Response Ready");
                str = new Scanner(rd).useDelimiter(">").next()+">";
                count = 501;
            }
            Thread.sleep(10);
            System.out.println ("Response Not Ready" + count);
            count ++;
        } while (count < 25);