2014-01-14 5 views
1

Мне нужна помощь по моему as400 и java-соединению.отложенный ответ, полученный в java-сокете

У меня возникла проблема с получением более позднего ответа во время SocketTimeoutExceptions. Итак, что происходит, когда я отправляю первый запрос и время ожидания ответа, после отправки моего второго запроса получен ответ для первого запроса, что создает несоответствие.

Есть ли способ, который после исключения таймаута ответ не должен кэшироваться или не должен быть получен после следующего запроса?

Ниже приведен фрагмент кода для подключения к серверу AS400:

public synchronized static byte[] sendRequestAndGetResponse(byte[] requestBytes) { 
    try { 
     if(checkHostConnection()){ 
      LOG.debug("Sending request bytes to Host: {}", Hexifier.toHex(requestBytes)); 
      IOUtils.write(requestBytes, dos); 
      long startTime = System.currentTimeMillis(); 
      LOG.info("Request sent to host."); 

      LOG.info("Waiting on host response"); 
      byte[] responseLengthBuffer = new byte[4]; 
      IOUtils.readFully(dis, responseLengthBuffer); 

      ByteBuffer bb = ByteBuffer.wrap(responseLengthBuffer); 
      int msgLength = bb.getInt(); 

      byte[] responseRemBytes = new byte[msgLength]; 
      IOUtils.readFully(dis, responseRemBytes); 
      long endTime = System.currentTimeMillis(); 

      byte[] fullResponseBytes = new byte[responseLengthBuffer.length + responseRemBytes.length]; 

      System.arraycopy(responseLengthBuffer, 0, fullResponseBytes, 0, responseLengthBuffer.length); 
      System.arraycopy(responseRemBytes, 0, fullResponseBytes, responseLengthBuffer.length, responseRemBytes.length); 
      LOG.debug("Response from server is received. Time elapsed at {} millis.", (endTime - startTime)); 
      LOG.debug("Bytes received: {}", Hexifier.toHex(fullResponseBytes)); 

      return fullResponseBytes; 

     } else { 
      reconnectToHost(); 
     } 

    } catch (SocketTimeoutException ste){ 
     LOG.error("Reading response from socket timeout: {}", ste.getClass().getName()); 

     try { 
      LOG.warn("Waiting for Host reply from its socket timeout."); 
      socket.shutdownInput(); 
      socket.shutdownOutput(); 

      int hostResponsefromTimeout = dis.read(); 
      if (hostResponsefromTimeout == -1){ 
       LOG.debug("Host has responded with -1"); 

      } else { 
       LOG.debug("Host responded with: {}", hostResponsefromTimeout); 
      } 

     } catch (Exception e){ 
      LOG.error("Error encountered while trying to validate if Host responded with last timeout."); 
      LOG.error(e.getMessage(), e); 

     } 


     reconnectToHost(); 

    } catch (EOFException eofe) { 
     LOG.debug("An error occurred while reading stream from Host socket connection: {}", eofe.getClass().getName()); 
     LOG.error(eofe.getMessage(), eofe); 

     if (eofe.getMessage() != null && eofe.getMessage().contains("actual: 0")){ 
      LOG.warn("No bytes were found at stream. Host did not respond."); 
     } 

     reconnectToHost(); 

    } catch (SocketException e) { 
     LOG.error("An error occurred while attempting to connect to Host: {}", e.getClass().getName()); 
     LOG.error(e.getMessage(), e); 

     if (e.getMessage().contains("Broken pipe")){ 
      LOG.debug("Connection to Host was lost."); 
     } 

     reconnectToHost(); 

    } catch (Exception e) { 
     LOG.error(e.getMessage(), e); 
     LOG.debug("An error occurred while attempting to connect to Host: {}", e.getClass().getName()); 
     reconnectToHost(); 
    } 

    return null; 
} 
+5

У вас есть код для обмена? – AxiomaticNexus

+0

Здравствуйте, см. Мой код – alvin

ответ

0

Если вы получаете SocketTimeoutException на сокете вы иначе планируете повторно использовать для другого запроса, закрыть его и не используйте для повторного использования. Избавьтесь от всего этого выключения и прочитайте код внутри обработчика catch и просто закройте сокет. Вы не можете получить «неправильный ответ» для последующего запроса в том же сокете.

Если вы получаете много тайм-аутов, ваш тайм-аут слишком короткий. Обычно это должно удвоить ожидаемое время обслуживания для соответствующего запроса.

+0

Здравствуйте, метод reconnectToHost() после исключения SocketTimeoutException закрывает сокеты и создает новый для другого запроса. Это моя первоначальная реализация, однако отложенный ответ по-прежнему ощущается. Я добавил объект shutdown и прочитанный код, чтобы убедиться, что я изящно отказался от соединения с Host: [link] (http://stackoverflow.com/questions/2028620/java-sockets-and-dropped-connections) – alvin

Смежные вопросы