有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用于检测和捕获SocketException的多线程Java

我有一个Java服务器/客户机应用程序,它使用while循环允许客户机输入,直到断开连接。这是在ClientHandler类对象内完成的,该类对象扩展了Thread并使用run()方法,因此每个连接的客户机都在其自己的线程上进行通信

到目前为止,情况就是这样:

public void run()
{
    //receive and respond to client input
    try
    {
        //strings to handle input from user
        String received, code, message;

        //get current system date and time
        //to be checked against item deadlines
        Calendar now = Calendar.getInstance();

        //get initial input from client
        received = input.nextLine();                

        //as long as last item deadline has not been reached
        while (now.before(getLastDeadline()))
        {   
            //////////////////////////////////
            ///processing of client message///
            //////////////////////////////////

            //reload current system time and repeat loop 
            now = Calendar.getInstance();

            //get next input from connected client
            received = input.nextLine();
            //run loop again
        }
    }
    //client disconnects with no further input
    //no more input detected
    catch (NoSuchElementException nseEx)
    {
        //output to server console
        System.out.println("Connection to bidder has been lost!");
        //no system exit, still allow new client connection
    }
}

这一切都很好,当客户机停止运行其程序时NoSuchElementException会被处理(因为不会有后续输入)

我想做的是检测客户端socket何时与服务器断开连接,以便服务器可以更新当前连接的客户端的显示。我被告知要通过捕捉SocketException来实现这一点,我已经阅读了这个异常,但仍然对如何实现它感到困惑

据我所知(尽管我可能错了),必须在客户端捕获SocketException。对吗?如果是这种情况,那么SocketException是否可以与我已经存在的NoSuchElementException协调运行,或者是否必须删除/替换该例外

关于如何结合抓捕SocketException的一个基本例子将是一个巨大的帮助,因为我在网上找不到任何相关的例子

谢谢

马克


共 (1) 个答案

  1. # 1 楼答案

    实际上,你已经抓住了SocketExceptionnextLine调用将(最终)对Socket返回的基础SocketInputStream调用read()。对read()的调用将抛出一个SocketException(它是IOException的子类)。Scanner类将捕获IOException,然后返回NoSuchElementException。所以你真的没什么需要做的了

    如果你想访问实际的SocketException,你可以在抓到NoSuchElementException后在Scanner上调用ioException。此外,如果您试图跟踪已连接客户端的列表,则必须在服务器端完成。您可以在客户端捕获SocketException,但这将表明服务器意外断开连接,而这并不是您真正想要的