【问题标题】:Differentiating between the data packets in TCP IP区分 TCP IP 中的数据包
【发布时间】:2015-06-07 10:40:03
【问题描述】:

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

服务器的相同代码(os 是缓冲的输出流):

            // 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
      }

【问题讨论】:

  • os.write((int)myFile.length()) 是 wrong 正如彼得劳里的回答所指出的那样。它写入一个值为myFile.length() & 0xFF 的字节。此外,在os.close() 之前不需要调用os.flush()。 close() 始终刷新任何核心 IO 类中的任何剩余数据。

标签: java tcp tcpclient


【解决方案1】:

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

对于阅读,您必须承担订单。即您假设先发送长度,然后发送内容。使用 DataInputStream.readInt() 读取长度。

【讨论】:

  • 谢谢彼得。我正在发送一个大小为 4mb 的文件。因此,当我使用 Datainputstream.readInt() 读取变量时,它会将其存储到该整数变量中吗?
  • 是的,一个 int 字段,它有剩余的长度可供读取。您可以在一次读取部分数据时减少此值。
猜你喜欢
  • 2016-04-19
  • 2016-12-31
  • 1970-01-01
  • 1970-01-01
  • 2015-02-05
  • 2012-03-30
  • 1970-01-01
  • 2012-08-20
  • 1970-01-01
相关资源
最近更新 更多