0

Java: 1.7 OS: Linux (but I don't know which Linux it is)

I have a CharBuffer to contain something I read from socket's BufferedReader. Socket was established that for sure, and when I'm trying to dump it, it gives me an ERROR_FORMAT result.

After that, I read data from socket but caused java.net.SocketException: Connection reset

The Connection reset problem was the problem I'm fixing, but how come CharBuffer.toString() gives an ERROR_FORMAT result ?

Below is my code, is there anything wrong ?

Socket connectionSocket=xxxxxx;  //Connected socket given by other library

connectionSocket.setSoTimeout(75*1000);
CharBuffer charBuffer=CharBuffer.allocate(1024);
BufferedReader bufferedReader=null;

bufferedReader=new BufferedReader(new InputStreamReader(connectionSocket.getInputStream(), "BIG5"));

while((bufferedReader.read(charBuffer))!=-1)  // in 2nd time, this line throw a java.net.SocketException: Connection reset
{
  charBuffer.flip();
  respStr.append(charBuffer);
  log.info("CharBuffer: "+charBuffer.toString());  // this line runs just 1 tine, print result: "CharBuffer: 2016102618353211301 : ERROR_FORMAT"
  charBuffer.clear();
}
log.info("CharBuffer all: "+charBuffer.toString());  // dodn't been execute
RRTW
  • 3,160
  • 1
  • 35
  • 54
  • It is possible that the characters in your data stream are not on the BMP which could cause problems. I would suggest you put the raw data in a ByteArraryInputStream instead of using socket until you figure out the problem. – BevynQ Oct 27 '16 at 05:22
  • What the BMP is ? – RRTW Oct 27 '16 at 06:33

1 Answers1

0

I was unable to replicate your issue

public static void main(String[] args) throws IOException {
    StringBuilder respStr = new StringBuilder();
    CharBuffer charBuffer=CharBuffer.allocate(1024);
    BufferedReader bufferedReader=null;
    Logger log = Logger.getAnonymousLogger();

    // create a byte stream with some big 5 characters in it
    // to simulate what a socket should produce
    byte[] bytes = new byte[100];
    int index = 0;
    for(int i = 0xc940;i<0xc940+50;i++){
        bytes[index++] = (byte)((i & 0x0ff00)>>8);
        bytes[index++] = (byte)((i & 0x0ff));
    }
    InputStream byteStream = new ByteArrayInputStream(bytes);

    // code to process the byte stream
    bufferedReader=new BufferedReader(new InputStreamReader(byteStream, "BIG5"));
    while((bufferedReader.read(charBuffer))!=-1){
        charBuffer.flip();
        respStr.append(charBuffer);
        log.info("CharBuffer: "+charBuffer.toString());
        charBuffer.clear();
    }
    log.info("CharBuffer all: "+charBuffer.toString());
}

Oct 27, 2016 6:27:18 PM nz.test.buffers.CharBufferTest main

INFO: CharBuffer: < chinese characters >

Oct 27, 2016 6:27:18 PM nz.test.buffers.CharBufferTest main

INFO: CharBuffer all: < chinese characters >

BevynQ
  • 8,089
  • 4
  • 25
  • 37