繁体   English   中英

(Java Multiclient服务器)当客户端关闭套接字并且服务器向客户端写入时,也不例外

[英](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
    }

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

任何帮助,将不胜感激。

  1. PrintWriter吞下异常。 请参阅Javadoc。
  2. 由于缓冲的原因,您永远不会在第一次写入已被对等方关闭的连接时获得异常。 您最终将获得“连接重置”。 但是永远不要第一次写。
  3. 绑定ServerSocket之后调用setReuseAddress()是完全没有意义的,就像在循环中调用它一样。

我认为您应该在完成一会儿时添加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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM