Search code examples
javatcptcpclient

Differentiating between the data packets in TCP IP


I have a case where the server sends the file size first and the file data. How do I differentiate both the integer value and the file data when being read at the client side?

Sameple code for server (os is the bufferedoutputstream):

            // Construct a 1K buffer to hold bytes on their way to the socket.
            byte[] mybytearray = new byte[(int) myFile.length()];

          //File Size
            os.write((int) myFile.length());

    FileInputStream fis = null;
    System.out.println("test+sendbytes");
    // Copy requested file into the socket's output stream.
      try {
          fis = new FileInputStream(myFile);
      } catch (FileNotFoundException ex) {
          // Do exception handling
      }
      BufferedInputStream bis = new BufferedInputStream(fis);

      try {
          bis.read(mybytearray, 0, mybytearray.length);
          os.write(mybytearray, 0, mybytearray.length);
          os.flush();
          os.close();
          os.close();

          // File sent, exit the main method
          return;
      } catch (IOException ex) {
          // Do exception handling
      }

Solution

  • You need to write the length as an int unless you are assuming all files arfe no more than 255 bytes long. Try DataOutputStream.writeInt()

    For the read you have to assume an order. ie you assume the length is sent first followed by the contents. Use DataInputStream.readInt() to read the length.