서버가 파일 크기와 파일 데이터를 먼저 보내는 경우가 있습니다. 클라이언트 측에서 읽을 때 정수 값과 파일 데이터를 어떻게 구분합니까? 서버에 대한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
}
''os.write ((int) myFile.length())'는 Peter Lawrey의 대답에서 지적한 바와 같이 잘못되었습니다. 값이 'myFile.length() & 0xFF' 인 단일 바이트를 씁니다. 또한'os.flush()'호출은'os.close()'바로 직전에 불필요합니다. 'close()'는 항상 핵심 IO 클래스의 나머지 데이터를 모두 비 웁니다. –