java.net.SocketException: Connection reset

前端 未结 10 1537
慢半拍i
慢半拍i 2020-11-22 03:02

I am getting the following error trying to read from a socket. I\'m doing a readInt() on that InputStream, and I am getting this error. Perusing th

10条回答
  •  借酒劲吻你
    2020-11-22 03:56

    You should inspect full trace very carefully,

    I've a server socket application and fixed a java.net.SocketException: Connection reset case.

    In my case it happens while reading from a clientSocket Socket object which is closed its connection because of some reason. (Network lost,firewall or application crash or intended close)

    Actually I was re-establishing connection when I got an error while reading from this Socket object.

    Socket clientSocket = ServerSocket.accept();
    is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    int readed = is.read(); // WHERE ERROR STARTS !!!
    

    The interesting thing is for my JAVA Socket if a client connects to my ServerSocket and close its connection without sending anything is.read() calls itself recursively.It seems because of being in an infinite while loop for reading from this socket you try to read from a closed connection. If you use something like below for read operation;

    while(true)
    {
      Receive();
    }
    

    Then you get a stackTrace something like below on and on

    java.net.SocketException: Socket is closed
        at java.net.ServerSocket.accept(ServerSocket.java:494)
    

    What I did is just closing ServerSocket and renewing my connection and waiting for further incoming client connections

    String Receive() throws Exception
    {
    try {                   
                int readed = is.read();
               ....
    }catch(Exception e)
    {
            tryReConnect();
            logit(); //etc
    }
    
    
    //...
    }
    

    This reestablises my connection for unknown client socket losts

    private void tryReConnect()
            {
                try
                {
                    ServerSocket.close();
                    //empty my old lost connection and let it get by garbage col. immediately 
                    clientSocket=null;
                    System.gc();
                    //Wait a new client Socket connection and address this to my local variable
                    clientSocket= ServerSocket.accept(); // Waiting for another Connection
                    System.out.println("Connection established...");
                }catch (Exception e) {
                    String message="ReConnect not successful "+e.getMessage();
                    logit();//etc...
                }
            }
    

    I couldn't find another way because as you see from below image you can't understand whether connection is lost or not without a try and catch ,because everything seems right . I got this snapshot while I was getting Connection reset continuously.

提交回复
热议问题