2017-12-04 2 views
1

Java 및 TCP를 사용하여 서버에서 클라이언트로 파일을 전송하려고하는데 클라이언트 측에서 소켓 예외가 발생하는 반면 서버는 시도 할 때 오류가 없습니다 파일을 전송할 수 있습니다. 소켓에서 읽으려고하기 전에 소켓을 닫지 않았기 때문에이 오류에 대해 혼란스러워합니다. 서버가 연결을 승인하고 파일을 전송하지만 클라이언트가 오류를 수신합니다. 어떠한 제안?파일을 전송하려고 할 때 소켓이 닫힌 예외가 발생했습니다.

오류 :

java.net.SocketException의는 :

System.out.println("Going to get the file..."); 
    socket = new Socket(response.getIP().substring(1), response.getPort()); 

    byte[] contents = new byte[10000]; 
    FileOutputStream fos = new FileOutputStream("hank.txt"); 
    BufferedOutputStream bos = new BufferedOutputStream(fos); 
    InputStream in = socket.getInputStream(); 

    int bytesRead = 0; 
    System.out.println("Starting to read file..."); 
    while((bytesRead = is.read(contents))!=-1) { //the error points to this lin 
     bos.write(contents,0,bytesRead); 
    } 

    bos.flush(); 
    bos.close(); 
    in.close(); 

    // 
    socket.close(); 
:

public void run() { 
    System.out.println("Service thread running for client at " + socket.getInetAddress() + " on port " + socket.getPort()); 
    try { 
     File file = new File("hank.txt"); 
     FileInputStream fis = new FileInputStream(file); 
     BufferedInputStream bis = new BufferedInputStream(fis); 
     OutputStream os = socket.getOutputStream(); 

     byte[] contents; 
     long fileLength = file.length(); 
     long current = 0; 

     long start = System.nanoTime(); 
     while(current!=fileLength) { 
      int size = 1000; 
      if(fileLength - current >= size) { 
       current += size; 
      } 
      else { 
       size = (int)(fileLength - current); 
       current = fileLength; 
      } 
      contents = new byte[size]; 
      bis.read(contents,0,size); 
      os.write(contents); 
      System.out.println("sending file..." + (current*100)/fileLength+"% complete!"); 
     } 
     os.flush(); 
     this.socket.close(); 
    }catch(Exception e) { 
     e.printStackTrace(); 
    } 
} 

클라이언트가 파일의 코드를 수신 : 소켓

서버 스레드의 실행 기능을 폐쇄

+0

변경 is.read (내용)) –

+0

당신에게 고정되도록 감사드립니다 (내용을)) in.read하는

InputStream in = socket.getInputStream(); 

에 변수 에서 사용할 수 있습니다 그것. "is"라는 ObjectInputStream이 있으므로 밑줄이 빨간색으로 표시되지 않습니다. 나는 결코 그것을 발견하지 못했다. – hjskeqwe

+0

더 나은 코드는 [소켓을 통한 Java 다중 파일 전송] (https://stackoverflow.com/questions/10367698/java-multiple-file-transfer-over-socket)을 참조한다. – EJP

답변

1
이 소켓

입력 스트림은 그래서

Change is.read(contents)) to in.read(contents)) 
+1

그 덕분에, 정말 고마워. 30 분 동안 멍청이처럼 보였습니다. – hjskeqwe

관련 문제