2012-04-14 2 views
1

서버가 파일 크기와 파일 데이터를 먼저 보내는 경우가 있습니다. 클라이언트 측에서 읽을 때 정수 값과 파일 데이터를 어떻게 구분합니까? 서버에 대한TCP IP에서 데이터 패킷을 구별

Sameple 코드 (OS가의 BufferedOutputStream입니다) : 모든 파일이 더 이상 255 이상의 바이트 arfe 가정하지 않는 한

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

''os.write ((int) myFile.length())'는 Peter Lawrey의 대답에서 지적한 바와 같이 잘못되었습니다. 값이 'myFile.length() & 0xFF' 인 단일 바이트를 씁니다. 또한'os.flush()'호출은'os.close()'바로 직전에 불필요합니다. 'close()'는 항상 핵심 IO 클래스의 나머지 데이터를 모두 비 웁니다. –

답변

1

당신은 int로 길이를 작성해야합니다. Try DataOutputStream.writeInt()

읽기 위해서는 주문해야합니다. 즉, 길이가 먼저 전송 된 다음 내용이 전송된다고 가정합니다. DataInputStream.readInt()를 사용하여 길이를 읽습니다.

+0

감사합니다. 피터. 나는 4MB 크기의 파일을 보내고있다. 그래서 Datainputstream.readInt()를 사용하여 변수를 읽었을 때, 그것을 intger 변수에 저장합니까? – DesperateLearner

+0

예, 읽을 수있는 길이의 'int'필드. 한 번에 데이터의 일부를 읽을 때이 값을 줄일 수 있습니다. –

관련 문제