簡體   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