2012-04-14 30 views
1

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

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 
     } 
+0

正如Peter Lawrey的答案中指出的那样,'os.write((int)myFile.length())'*错误*。它使用值myFile.length()&0xFF'写入一个字节。另外,在os.close()之前调用'os.flush()'是不必要的。 'close()'总是刷新任何核心IO类中的剩余数据。 – 2012-04-14 12:04:28

回答

1

你需要写长度为int除非你是假设所有文件arfe不超过255个字节。尝试DataOutputStream.writeInt()

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

+0

谢谢彼得。我发送的文件大小为4mb。所以当我将Datainputstream.readInt()读入一个变量时,它会将它存储到该变量中吗? – DesperateLearner 2012-04-14 10:26:00

+0

是的,一个'int'字段,其长度可以读取。您可以一次读取部分数据来减少此数据。 – 2012-04-14 10:28:18