2016-07-08 82 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[])

相关问题