javasocketsdatainputstream

java socket DataInputStream


I have a multithreaded program java java socket and I receive the information bizare. like this ¤¤¤¤¤¤23456718900263678722¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤

public void run() 
       {
            try {

                byte[] bs = new byte[64];

                 // read data into buffer
                 dataReception.read(bs);

                 // for each byte in the buffer
                 for (byte b:bs)
                 {
                    // convert byte into character
                    char c = (char)b;

                    // print the character
                    System.out.print(c);
                 }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

Solution

  • The problem is here:

    // read data into buffer
    dataReception.read(bs);
    

    Read doesn't read exactly that amount of bytes that you want to have in that array. It can read any number of bytes. Therefore you always have to check the return value of the read operation; and only when all expected bytes were read ... you should continue!

    The reason that your output looks like garbage is this not that you would be receiving special characters.

    What happens is:

    This can be verified by printing your array before reading. You will see that only contains those "special" characters.