简体   繁体   English

区分TCP IP中的数据包

[英]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): 服务器的相同代码(os是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
      }

You need to write the length as an int unless you are assuming all files arfe no more than 255 bytes long. 除非假设所有文件的长度不超过255个字节,否则您需要将长度写为int Try DataOutputStream.writeInt() 试试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. 使用DataInputStream.readInt()读取长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM