2012-02-28 3 views
0

소켓을 통해 서버 프로그램에서 클라이언트 프로그램으로 파일을 보내는데 문제가 있습니다. 그래서 공정한 바이트로 분할 시도했지만 지금까지 어떤 성공도 없었습니다. 또한 서버가 동시 적이어야하므로 파일을 전송할 코드를 어디에 넣어야하는지 확신 할 수 없습니다.Java 소켓에서 파일 보내기

감사

편집 : 여기

내가 지금까지 시도 코드가 그것으로 파일의 복사본을 전송하는 순간에, 자사 될 운명하지만 파일 크기가 0 바이트입니다 : (

프로토콜 클래스에서

:

try { 
    File program = new File("./src/V2AssignmentCS/myProgram.jar"); 

byte[] mybytearray = new byte[4096]; 

FileInputStream fis = new FileInputStream(program); 

BufferedInputStream bis = new BufferedInputStream(fis); 

bis.read(mybytearray, 0, mybytearray.length); 

OutputStream os = sock.getOutputStream(); 

System.out.println("Sending..."); 

os.write(mybytearray, 0, mybytearray.length); 

os.flush(); 

} catch (IOException e) { 

     System.err.println("Input Output Error: " + e); 

    } 

그리고 클라이언트 측 :

long start = System.currentTimeMillis(); 
int bytesRead; 
int current = 0; 
// localhost for testing 

// receive file 
byte [] mybytearray = new byte [ServerResponse.programSize()]; 
InputStream is = sock.getInputStream(); 
FileOutputStream fos = new FileOutputStream("./src/V2AssignmentCS/newProgram.jar"); 
BufferedOutputStream bos = new BufferedOutputStream(fos); 
bytesRead = is.read(mybytearray,0,mybytearray.length); 
current = bytesRead; 

// thanks to A. Cádiz for the bug fix 
do { 
    bytesRead = 
     is.read(mybytearray, current, (mybytearray.length-current)); 
    if(bytesRead >= 0) current += bytesRead; 
} while(bytesRead > -1); 

bos.write(mybytearray, 0 , current); 
bos.flush(); 
long end = System.currentTimeMillis(); 
System.out.println(end-start); 
bos.close(); 
sock.close(); 
+2

"문제 음 ... 나는 어떤 없었 다음과 같이

bytesRead = is.read(mybytearray,0,mybytearray.length); current = bytesRead; // thanks to A. Cádiz for the bug fix do { bytesRead = is.read(mybytearray, current, (mybytearray.length-current)); if(bytesRead >= 0) current += bytesRead; } while(bytesRead > -1); 

당신이 양쪽 끝에 를 사용한다 자바에서 스트림을 복사 할 수있는 표준 방법,입니다 성공은 지금까지 ". 유용한 정보가 없습니다. 당신의 실제 질문은 무엇입니까? 어떤 Java 코드와 관련이 있습니까? – EJP

답변

3
bis.read(mybytearray, 0, mybytearray.length); 

이 메서드에서 반환 된 결과 코드는 무시됩니다. Javadoc을 확인하십시오. 당신이 분명히 기대하는 바가 아닙니다.

os.write(mybytearray, 0, mybytearray.length); 

여기 정확히 4096 바이트를 쓰고 있습니다. 그것이 당신의 의도였습니까?

int count; 
byte[] buffer = new byte[8192]; // or whatever you like 
while ((count = in.read(buffer)) > 0) 
{ 
    out.write(buffer, 0, count); 
} 
out.close(); 
in.close(); 
관련 문제