套接字读取数据的时间太长(BufferedReader)

时间:2016-07-08 09:20:11

标签: java sockets io

我正在从交换机读取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

3 个答案:

答案 0 :(得分:2)

您发布的输出不包含行,因此readLine()不合适,并且您希望一次发送一条消息,因此IOUtils.toByteArray()不是{\ n}适当的。试试,呃,read(byte[])

答案 1 :(得分: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.
}

为了简洁,我省略了异常处理。

答案 2 :(得分:0)

猜猜:message = in.readLine();等到endofLine \ n。也许你不发送一些,或者你错过了冲洗发送插座/流。