【问题标题】:Java - Where to detect and catch SocketExceptionJava - 在哪里检测和捕获 SocketException
【发布时间】:2016-03-13 18:01:12
【问题描述】:

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

到目前为止发生的事情是这样的:

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 在客户端停止运行他们的程序时被处理(因为不会有后续输入)。

我想要做的是检测客户端套接字何时与服务器断开连接,以便服务器可以更新当前连接客户端的显示。我被告知要通过捕获 SocketException 来执行此操作,并且我已经阅读了此异常,但仍然对如何实现它感到有些困惑。

据我了解(尽管我可能是错的),SocketException 必须在客户端捕获。这个对吗?如果是这种情况,SocketException 能否与我已有的 NoSuchElementException 协调运行,还是必须删除/替换该异常?

一个如何结合捕获SocketException 的基本示例将是一个巨大的帮助,因为我无法在网上找到任何相关示例。

谢谢,

标记

【问题讨论】:

    标签: java multithreading sockets


    【解决方案1】:

    实际上,您已经收到了SocketExceptionnextLine 调用将(最终)在Socket 返回的底层SocketInputStream 上调用read()。对read() 的调用将抛出SocketException(它是IOException 的子类)。 Scanner 类将捕获IOException,然后返回NoSuchElementException。所以你真的没有什么需要做的了。

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

    【讨论】:

      猜你喜欢
      • 2020-01-11
      • 1970-01-01
      • 2011-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      相关资源
      最近更新 更多