(Java 多客户端服务器) 客户端关闭套接字和服务器写入客户端时无异常

(Java Multiclient server) No exception when client closes socket and server writes to client

服务器代码:

public class Main {
    public static void main(String args[]){
        Socket s=null;
        ServerSocket ss2=null;
        System.out.println("Server Listening......");
        try{
            ss2 = new ServerSocket(8080);
        }
        catch(IOException e){
            e.printStackTrace();
            System.out.println("Server error");
        }

        while(true){
            try{
                s = ss2.accept();
                ss2.setReuseAddress(true);
                System.out.println("connection Established");
                ServerThread st=new ServerThread(s);
                st.start();
            }
            catch(Exception e){
                e.printStackTrace();
                System.out.println("Connection Error");
            }
        }
    }
}

class ServerThread extends Thread{  

    String line; = "testing";
    PrintWriter os=null;
    Socket s=null;

    public ServerThread(Socket s){
        this.s=s;
    }

    public void run() {
        try{
            os=new PrintWriter(s.getOutputStream());

        }catch(IOException e){
            System.out.println("IO error in server thread");
        }

        try {
            for (int i = 0 ; i < 100 ; i++){
                os.println(line);
                os.flush();
                Thread.sleep(1000);
            }
        }
        catch(NullPointerException | IOException | InterruptedException e){
            System.out.println("Client "+line+" Closed");
        }

        finally{    
            try{
                System.out.println("Connection Closing..");

                if(os!=null){
                    os.close();
                    System.out.println("Socket Out Closed");
                }
                if (s!=null){
                s.close();
                System.out.println("Socket Closed");
                }

                }
            catch(IOException ie){
                System.out.println("Socket Close Error");
            }
        }//end finally
    }

当客户端连接到服务器时,服务器开始打印ln。但是当client关闭socket时,server仍然保留着println。假设服务器会抛出异常?

如有任何帮助,我们将不胜感激。

我认为你应该在完成 while

时添加 ss2.close()s.close()
while(true){
    try{
    s = ss2.accept();
    ss2.setReuseAddress(true);
    System.out.println("connection Established");
    ServerThread st=new ServerThread(s);
    st.start();
    }
    catch(Exception e){
        e.printStackTrace();
        System.out.println("Connection Error");
     }
 }
 ss2.close();
 s.close();
  1. PrintWriter 吞下异常。请参阅 Javadoc。
  2. 出于缓冲原因,您永远不会在第一次写入已被对等方关闭的连接时出现异常。你最终会得到一个'connection reset'。但从来没有在第一次写。
  3. 在绑定 ServerSocket 之后调用 setReuseAddress() 是完全没有意义的,就像在循环中调用它一样。