服务器关闭时,Java Socket没有异常

时间:2018-11-04 22:02:18

标签: java sockets exception-handling

有人可以给我一些支持吗:我有这些客户端和服务器套接字类:

public class Client {
    public static void main(String[] args) {
        String servername = "localhost";
        int port = 21000;
        Socket sc = null;
        boolean test = true;

        while(test) {
            try {
                sc = new Socket(servername, port);
                PrintWriter out = new PrintWriter(sc.getOutputStream(), true);
                for(int i = 0; i < 100 ; i++) {
                    out.println("number " + i + " transmitted !");
                    System.out.println("number " + i + " transmitted !");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                test = false;
            } catch (IOException e1) {
                e1.printStackTrace();
                try {
                    sc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                continue;
            }
        }
    }
}


public class Server {
    public static void main(String[] args) {
        int port = 21000;

        try(ServerSocket serverSocket = new ServerSocket(port);
            Socket sc = serverSocket.accept();
            BufferedReader in = new BufferedReader(new InputStreamReader(sc.getInputStream())); ) {             
            String inputLine;               
            while((inputLine = in.readLine()) != null) {
                System.out.println("Received message : " + inputLine + " from " + sc.toString());   
            }
        } catch(IOException e) {
            System.out.println("Error : " + e.getMessage());
        }
    }
}

当我启动服务器然后启动客户端时,我看到它可以正常工作,但是当我在客户端的计数器结束之前残酷地停止服务器时,我看不到客户端出现任何异常,并且该异常继续就像服务器仍然在那一样。当服务器不再存在时,我想举个例子。

0 个答案:

没有答案