【发布时间】: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