Java—在何处检测和捕获SocketException
我有一个Java服务器/客户端应用程序,它使用Java—在何处检测和捕获SocketException,java,multithreading,sockets,Java,Multithreading,Sockets,我有一个Java服务器/客户端应用程序,它使用while循环,允许客户端输入直到断开连接。这是在一个ClientHandler类对象内完成的,该类对象扩展Thread,并使用run()方法,因此每个连接的客户端都在其自己的线程上进行通信 目前发生的情况如下: public void run() { //receive and respond to client input try { //strings to handle input from user
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
}
}
这一切都可以正常工作,当客户端停止运行其程序时,NoTouchElementException
会被处理(因为不会有后续输入)
我想做的是检测客户端套接字何时与服务器断开连接,以便服务器可以更新当前连接的客户端的显示。我被告知要通过捕获SocketException
来实现这一点,我已经阅读了这个异常,但仍然对如何实现它感到有点困惑
据我所知(尽管我可能错了),必须在客户端捕获SocketException
。这是正确的吗?如果是这种情况,SocketException
是否可以与我已经存在的NoSuchElementException
协调运行,或者是否必须删除/替换该异常
关于如何合并捕获一个SocketException
的基本示例将是一个巨大的帮助,因为我在网上找不到任何相关示例
谢谢
标记实际上您已经捕获了
SocketException
。nextLine
调用将(最终)对由Socket
返回的底层SocketInputStream
调用read()
。调用read()
将抛出SocketException
(它是IOException
的子类)。Scanner类将捕获IOException
,然后返回NoSuchElementException
。所以你真的没什么需要做的了
捕捉到NoTouchElementException
后,您可以通过调用扫描仪上的ioException
来访问实际的SocketException
。此外,如果您试图跟踪已连接客户端的列表,则必须在服务器端完成此操作。您可以在客户端捕获一个SocketException
,但这表明服务器意外断开了连接,这并不是您真正想要的