如何在Java 1.4中设置BufferedReader和PrintWriter的超时? [英] How do you set a timeout on BufferedReader and PrintWriter in Java 1.4?

查看:188
本文介绍了如何在Java 1.4中设置BufferedReader和PrintWriter的超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在BufferedReader和使用套接字连接创建的PrintWriter上设置超时?这是我现在为服务器提供的代码,直到服务器或客户端崩溃为止:

How does one set a timeout on a BufferedReader and a PrintWriter created using a socket connection? Here is the code I have for the server right now, which works until either the server or the client crashes:

while(isReceiving){
    str = null;
    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);

    while ((str = br.readLine()) != null){
        System.out.println("Processing command " + str);
        pw.println(client.message(str));
    }
}

在此代码范围之外我强加了一个套接字超时1000毫秒,在等待初始连接时按预期工作。但程序阻塞(str = br.readLine())。如果客户端挂起或崩溃,它永远不会停止阻止,除非我终止进程(即使这样也不总是有效)。

Outside the scope of this code I have imposed a socket timeout of 1000ms, which works as intended when waiting for the initial connection. But the program blocks at (str = br.readLine()). If the client hangs or crashes, it never stops blocking unless I terminate the process (which even then doesn't always work).

有问题的客户端代码非常相似对此,并以类似的方式阻塞。

The client code in question is very similar to this, and is blocking in a similar fashion.

推荐答案

因为调用socket.close()似乎没有中断块在br.readLine(),我做了一些解决方法。当断开客户端与服务器的连接时,我只是通过字符串bye发送,并告诉服务器在收到此命令时关闭套接字连接。

Since calling socket.close() did not seem to interrupt the block at br.readLine(), I did a little workaround. When disconnecting the client from the server, I merely send through a string "bye", and told the server to close the socket connection when it receives this command.

while ((str = br.readLine()) != null){
    // If we receive a command of "bye" the RemoteControl is instructing
    // the RemoteReceiver to close the connection.
    if (str.equalsIgnoreCase("bye")){
        socket.close();
            break;
    }
    System.out.println("Processing command " + str);
    pw.println(client.message(str));
}

这篇关于如何在Java 1.4中设置BufferedReader和PrintWriter的超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆