gpt4 book ai didi

Java - 在哪里检测和捕获 SocketException

转载 作者:行者123 更新时间:2023-11-30 10:48:03 27 4
gpt4 key购买 nike

我有一个 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 的基本示例将是一个巨大的帮助,因为我无法在网上找到任何相关示例。

谢谢,

标记

最佳答案

您实际上已经捕获了 SocketExceptionnextLine 调用将(最终)调用 Socket 返回的底层 SocketInputStream 上的 read()。此对 read() 的调用将抛出 SocketException(它是 IOException 的子类)。 Scanner 类将捕获 IOException,然后返回 NoSuchElementException。所以您真的不需要再做任何事情了。

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

关于Java - 在哪里检测和捕获 SocketException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35973756/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com