2016-07-08 83 views
0

我正在讀取來自交換機的ISO消息,並且其讀取時間過長。如果在8秒內沒有收到回覆,它甚至可以花費兩分鐘時間讀取整個流並切換超時。有沒有使用BufferedReader從套接字獲得輸入流的另一種方法?套接字花費太長的時間來讀取數據(緩衝讀取器)

 s = new ServerSocket(8777); 

     echo("Server socket created.Waiting for connection..."); 
     //get the connection socket 
     conn = s.accept(); 
     echo("Connection received from " + conn.getInetAddress().getHostName() + " : " + conn.getPort()); 

     //3. get Input and Output streams 
     out = new PrintStream(conn.getOutputStream()); 
     //out.flush(); 
     System.out.println(new Date()); 
     //in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
     System.out.println(new Date()); 
     InputStream in = conn.getInputStream(); 
     message = in.readLine(); 
     echo("client>" + message); 
     System.out.println(new Date()); 

這裏你可以看到差異日誌從它開始讀,直到它輸出的消息

Server socket created.Waiting for connection... 
Connection received from 11.xx.xx.xx : 51639 
Fri Jul 08 11:53:48 EAT 2016 
Fri Jul 08 11:53:48 EAT 2016 
client>ISO8583-9300004918040387042160708122130801ISO8583- 9300004918040387049160708122230802 
Fri Jul 08 11:55:51 EAT 2016 
+0

我想交換機不會以newLine結束傳輸 - 因此是延遲。嘗試讀取沒有BufferedReader的字節。片段中是否存在複製和粘貼錯誤?有兩個聲明。不應該編譯。 – Fildor

+0

仍然無法正常工作。我嘗試過使用這段代碼,但延遲仍然存在 InputStream in = conn.getInputStream(); byte [] bytes = IOUtils.toByteArray(in); // message = in.readLine(); echo(「client>」+ bytes.toString()); System.out.println(new Date()); –

+0

「此方法在內部緩衝輸入,因此不需要使用BufferedInputStream。」只需從InputStream中讀取一些合理大小的'byte []緩衝區'即可。 – Fildor

回答

1

我想你應該使用read(byte[])並以某種方式檢測消息的結尾。

我不熟悉ISO8583,所以你必須弄清楚。可能會是它是一個固定長度的消息協議,或者有一個可以檢測到的消息終止符。

一個典型的例子是:

private static final int BUFFER_SIZE = 1024; // Or other reasonable value 

// ... 

byte[] buffer = new byte[BUFFER_SIZE]; 
int bytesRead = 0; 

// assuming you got the InputStream as "input" 
while ((bytesRead = input.read(buffer)) > 0){ // -1 indicates EOF 
    // read bytes are now in buffer[0..bytesRead-1] 
    // analyse bytes to maybe add up multiple reads to a complete message. 
} 

我離開了異常處理簡潔。

+0

循環條件應該是'> '。如果緩衝區長度爲零,則只能得到零,並且這不是您想要循環的條件:它不會讓您到達任何地方。只是一個錯誤。 – EJP

+0

@EJP oops。你是對的。已經更正。 – Fildor

+0

感謝它的工作,我已經使用了一個ByteArrayOutputStream和它不再拖延了。但現在的問題是,當我第一次寫入流時,即使在下一次我寫入前一條消息仍然存在時我將其刷新。 'ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFFER_SIZE); ((bytesRead = in.read(bytes))> 0){ baos.flush(); baos.write(bytes,0,BUFFER_SIZE); out.println(「response」+ baos.toString(「UTF-8」)); System.out.println(baos.toString(「UTF-8」));當你收到一個完整的消息並且只寫入你收到的字節數時,清除緩衝區。「#: }' –

0

猜測時間大約兩分鐘:消息= in.readLine();等待行程結束\ n。也許你不發送一些,或者你想要衝洗髮送套接字/流。

1

您發佈的輸出不包含行,因此readLine()不合適,並且您希望一次一條消息,因此IOUtils.toByteArray()也不合適。試試吧,錯誤,read(byte[])

相關問題