繁体   English   中英

区分TCP IP中的数据包

[英]Differentiating between the data packets in TCP IP

我有一种情况,服务器首先发送文件大小和文件数据。 在客户端读取时,如何区分整数值和文件数据?

服务器的相同代码(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
      }

除非假设所有文件的长度不超过255个字节,否则您需要将长度写为int 试试DataOutputStream.writeInt()

对于阅读,您必须假设一个命令。 即,您假设先发送长度,然后发送内容。 使用DataInputStream.readInt()读取长度。

暂无
暂无

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

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