developer tip

java.net.SocketException : 연결 재설정

optionbox 2020. 7. 27. 07:51
반응형

java.net.SocketException : 연결 재설정


소켓에서 읽으려고 할 때 다음 오류가 발생합니다. readInt()에 대한 작업을 수행 InputStream중이며이 오류가 발생합니다. 설명서를 숙지하면 연결의 클라이언트 부분이 연결을 닫았 음을 나타냅니다. 이 시나리오에서는 서버입니다.

클라이언트 로그 파일에 액세스 할 수 있으며 연결을 닫지 않으며 실제로 해당 로그 파일은 연결을 닫을 것을 제안합니다. 그렇다면 왜 이런 일이 일어나고 있는지 아는 사람이 있습니까? 무엇을 확인해야합니까? 임계 값에 도달 한 로컬 자원이있을 때 이런 현상이 발생합니까?


다음 줄이 있습니다.

socket.setSoTimeout(10000);

직전에 readInt(). 이것에 대한 이유가 있지만 (긴 이야기), 단지 궁금한 점이 있는데 이것이 표시된 오류로 이어질 수있는 상황이 있습니까? IDE에서 서버를 실행 중이고 IDE가 중단 점에 머물러있게 된 후 IDE의 내 로그에 똑같은 오류가 나타나기 시작했습니다.

어쨌든, 그냥 언급하면, 붉은 청어가 아니길 바랍니다. :-(


몇 가지 가능한 원인이 있습니다.

  1. 다른 쪽 끝은 여기서 문서화하지 않는 방식으로 의도적으로 연결을 재설정했습니다. 응용 프로그램 소프트웨어에서이 작업을 수행하는 경우는 드물고 일반적으로 올바르지 않지만 상용 소프트웨어로는 알 수 없습니다.

  2. 더 일반적으로, 다른 쪽 끝이 이미 정상적으로 닫힌 연결에 쓰면 발생합니다. 즉, 응용 프로그램 프로토콜 오류입니다.

  3. 소켓 수신 버퍼에 읽지 않은 데이터가있을 때 소켓을 닫아서 발생할 수도 있습니다.

  4. Windows에서 '연결 재설정'과 동일하지 않은 '소프트웨어로 인한 연결 중단'은 끝에서 보내는 네트워크 문제로 인해 발생합니다. 이에 대한 Microsoft 기술 자료 문서가 있습니다.


연결 재설정은 단순히 TCP RST가 수신되었음을 의미합니다. 피어가 처리 할 수없는 데이터를 수신하면 여러 가지 이유가있을 수 있습니다.

가장 간단한 방법은 소켓을 닫은 다음 출력 스트림에 더 많은 데이터를 쓰는 것입니다. 소켓을 닫으면 피어에게 말을 마치고 연결을 잊을 수 있습니다. 어쨌든 해당 스트림에서 더 많은 데이터를 보내면 피어는 RST로 거부하여 수신 중이 아니라는 것을 알려줍니다.

다른 경우에는 중재 방화벽이나 심지어 원격 호스트 자체가 TCP 연결을 "잊어 버릴"수 있습니다. 오랜 시간 동안 데이터를 보내지 않거나 (2 시간은 일반적으로 시간이 초과 됨) 피어가 재부팅되어 활성 연결에 대한 정보가 손실되어 발생할 수 있습니다. 이러한 연결이 끊긴 연결 중 하나에서 데이터를 보내면 RST도 발생합니다.


추가 정보에 대한 응답으로 업데이트 :

의 취급을 자세히 살펴보십시오 SocketTimeoutException. 소켓 조작에서 차단 된 상태에서 구성된 제한 시간을 초과하면이 예외가 발생합니다. 이 예외가 발생해도 소켓 자체의 상태는 변경되지 않지만 예외 처리기가 소켓을 닫은 다음 소켓에 쓰려고하면 연결 재설정 조건에있게됩니다. 다른 스레드에서 소켓을 닫는 것과 같은 더러운 작업을 수행하지 않고 영원히 차단 될 수 setSoTimeout()있는 read()작업 에서 벗어날 수있는 깔끔한 방법을 제공하기위한 것입니다.


이와 같은 이상한 문제가 생길 때마다 보통 WireShark같은 도구 를 사용하여 원시 데이터가 앞뒤로 전달되는 것을 살펴 봅니다. 연결이 끊어진 위치에 놀랄 수 있으며 시도하고 읽을 때만 알림을 받습니다.


당황 스럽지만이 문제가 발생했을 때 모든 데이터를 읽기 전에 연결을 닫는 것은 실수였습니다. 작은 문자열이 반환되는 경우에는 효과가 있었지만 닫기 전에 전체 응답이 버퍼링되었을 수 있습니다.

더 많은 양의 텍스트가 리턴되는 경우, 버퍼가 더 많이 리턴되므로 예외가 발생했습니다.

이 감독을 확인할 수 있습니다. URL을 여는 것은 파일과 같습니다. 일단 읽은 후에는 반드시 연결을 해제하십시오.


전체 추적을 매우 신중하게 검사해야합니다.

서버 소켓 응용 프로그램을 작성하고 java.net.SocketException: Connection reset사례를 수정했습니다 .

내 경우에는 Socket어떤 이유로 인해 연결이 닫힌 clientSocket 객체를 읽는 동안 발생합니다 . (네트워크 손실, 방화벽 또는 응용 프로그램 충돌 또는 의도 된 닫기)

실제로이 Socket 객체를 읽는 동안 오류가 발생했을 때 연결을 다시 설정했습니다.

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

흥미로운 점은 for my JAVA Socket클라이언트가 내 ServerSocket자신에게 연결하고 아무 것도 is.read()재귀 없이 호출 하지 않고 연결을 닫는 경우입니다. 이 소켓에서 읽을 수있는 무한 while 루프이기 때문에 닫힌 연결에서 읽으려고합니다. 읽기 작업에 아래와 같은 것을 사용하는 경우;

while(true)
{
  Receive();
}

그런 다음 아래와 같이 stackTrace를 얻습니다.

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.

enter image description here


I had the same error. I found the solution for problem now. The problem was client program was finishing before server read the streams.


I had this problem with a SOA system written in Java. I was running both the client and the server on different physical machines and they worked fine for a long time, then those nasty connection resets appeared in the client log and there wasn't anything strange in the server log. Restarting both client and server didn't solve the problem. Finally we discovered that the heap on the server side was rather full so we increased the memory available to the JVM: problem solved! Note that there was no OutOfMemoryError in the log: memory was just scarce, not exhausted.


I also had this problem with a Java program trying to send a command on a server via SSH. The problem was with the machine executing the Java code. It didn't have the permission to connect to the remote server. The write() method was doing alright, but the read() method was throwing a java.net.SocketException: Connection reset. I fixed this problem with adding the client SSH key to the remote server known keys.


Check your server's Java version. Happened to me because my Weblogic 10.3.6 was on JDK 1.7.0_75 which was on TLSv1. The rest endpoint I was trying to consume was shutting down anything below TLSv1.2.

By default Weblogic was trying to negotiate the strongest shared protocol. See details here: Issues with setting https.protocols System Property for HTTPS connections.

I added verbose SSL logging to identify the supported TLS. This indicated TLSv1 was being used for the handshake.
-Djavax.net.debug=ssl:handshake:verbose:keymanager:trustmanager -Djava.security.debug=access:stack

I resolved this by pushing the feature out to our JDK8-compatible product, JDK8 defaults to TLSv1.2. For those restricted to JDK7, I also successfully tested a workaround for Java 7 by upgrading to TLSv1.2. I used this answer: How to enable TLS 1.2 in Java 7

참고URL : https://stackoverflow.com/questions/62929/java-net-socketexception-connection-reset

반응형