区分TCP IP中的数据包

时间:2012-04-14 10:08:21

标签: java tcp tcpclient

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

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

1 个答案:

答案 0 :(得分:1)

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

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