2014-09-10 2 views
1

소켓 프로그래밍을 사용하여 두 대의 컴퓨터간에 통신을 시도하고 있습니다.Java 소켓 프로그래밍을 사용하여 두 대의 컴퓨터간에 파일을주고받습니다.

기본적으로 두 컴퓨터 모두 파일을 보내고받을 수 있어야합니다. 아래에 붙여 넣을 코드는 오류를 표시하지 않지만 서버 측 프로그램은 무기한으로 실행중인 것처럼 보입니다. 즉, 종료되지 않습니다. 여기에 붙어있는 주석으로 표시된 줄에 붙어 있습니다.

이 코드에서 처음에는 서버가 "file.txt"라는 파일을 보내고 클라이언트가 파일을 받고 이름을 "copy.txt"로 저장합니다. 나중에 클라이언트가 "file2.txt"라는 파일을 보내고 서버가 "copy2.txt"라는 이름으로 파일을 받고 저장하고 있습니다.

누군가 오류를 알려주고 개선점을 제안 할 수 있습니까?

//server side code 

import java.net.*; 
import java.io.*; 
public class server 
{ 
public static void main (String [] args) throws IOException 
{ 

    //sending file started 
    ServerSocket serverSocket = new ServerSocket(16167); 
    Socket socket = serverSocket.accept(); 
    System.out.println("Accepted connection : " + socket); 
    File transferFile = new File ("/Users/abhishek/desktop/file.txt"); 
    byte [] bytearray = new byte [(int)transferFile.length()]; 
    FileInputStream fin = new FileInputStream(transferFile); 
    BufferedInputStream bin = new BufferedInputStream(fin); 
    bin.read(bytearray,0,bytearray.length); 
    OutputStream os = socket.getOutputStream(); 
    System.out.println("Sending Files..."); 
    os.write(bytearray,0,bytearray.length); 
    os.flush(); 
    System.out.println("File transfer complete"); 
    //socket.close(); 
    //sending comleted 

    //receiving file started 
    int filesize=1022386; 
    int bytesRead=0; 
    int currentTot = 0; 
    byte [] bytearray1 = new byte [filesize]; 

    InputStream is = socket.getInputStream(); 

    FileOutputStream fos = new FileOutputStream("/Users/abhishek/desktop/copy2.txt"); 
    //fos.flush(); 
    BufferedOutputStream bos = new BufferedOutputStream(fos); 
    //bos.flush(); 
    System.out.println("not moving ahead!!!");//program stucked here 
    bytesRead = is.read(bytearray1,0,bytearray1.length); 
    currentTot = bytesRead; 
    System.out.println("current"+currentTot); 
    do 
    { 
     bytesRead = is.read(bytearray1, currentTot, (bytearray1.length-currentTot)); 
     if(bytesRead >= 0) 
      currentTot += bytesRead; 
     System.out.println("current"+currentTot); 
    } while(bytesRead > -1); 
    System.out.println("outside current"+currentTot); 
    bos.write(bytearray1, 0 , currentTot); 
    bos.flush(); 
    //receiving complete 
    System.out.println("Receving file completed"); 
    socket.close(); 

} 
} 



//client side code 
import java.net.*; 
import java.io.*; 


public class client 
{ 
    public static void main (String [] args) throws IOException 
    { 
     int filesize=1022386; 
     int bytesRead=0; 
     int currentTot = 0; 
     Socket socket = new Socket("localhost",16167); 
     byte [] bytearray = new byte [filesize]; 
     InputStream is = socket.getInputStream(); 
     FileOutputStream fos = new FileOutputStream("/Users/abhishek/desktop/copy.txt"); 
     BufferedOutputStream bos = new BufferedOutputStream(fos); 
     bytesRead = is.read(bytearray,0,bytearray.length); 
     currentTot = bytesRead; 
     do 
     { 
      bytesRead = is.read(bytearray, currentTot, (bytearray.length-currentTot)); 
      if(bytesRead >= 0) 
       currentTot += bytesRead; 
     } while(bytesRead > -1); 
     System.out.println("current"+currentTot); 
     bos.write(bytearray, 0 , currentTot); 
     bos.flush(); 
     bos.close(); 
     System.out.println("receiving first file completed!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); 

     //sending file 
     System.out.println("sending second file started!"); 
     File transferFile = new File ("/Users/abhishek/desktop/file2.txt"); 
     byte [] bytearray2 = new byte [(int)transferFile.length()]; 
     FileInputStream fin = new FileInputStream(transferFile); 
     BufferedInputStream bin = new BufferedInputStream(fin); 
     bin.read(bytearray2,0,bytearray2.length); 
     OutputStream os = socket.getOutputStream(); 
     os.flush(); 
     os.write(bytearray2,0,bytearray2.length); 
     os.flush(); 
     System.out.println("sending second file completed!"); 
     //sending complete 


     socket.close(); 
    } 
} 

답변

-1

난 당신이 정말 갇히지있는 곳

bytesRead = is.read(bytearray1,0,bytearray1.length);

이 셨을 ​​텐데요. 문제가 정상적으로 여기에 붙어 있다면 의사 소통의 다른 쪽은 아무런 데이터도 보내지 않았고, 읽을 것도없고, 쓰레드가 보내기를 기다리는 걸 멈췄다는 것입니다. 클라이언트 측

, 당신은 첫 번째 메시지를 전송 한 후

bos.close();

를 호출합니다. 이것은 소켓을 닫아서 서버 끝에서 IOException을 던지고 IOException을 잡아 내지 못하기 때문에 서버 프로그램이 종료됩니다.

얼마나 소켓 경험이 있습니까? 방금 소켓으로 시작한다면 ServerSocketExDataFetcher으로 시작하는이 확장 프로그램을 확인해보십시오.

+0

댓글에 대한 느낌이 들었습니다. – tilpner

+0

@StackOverflowException 질문 된 질문에 답변하고 제안 된 조언을 포함하도록 업데이트했습니다. – ControlAltDel

+0

네, 그게 내가 갇혀있는 곳입니다. 처음으로 소켓 프로그래밍을하고 있기 때문에이 상황을 피할 수있는 방법을 알려 주시기 바랍니다.또한, 내 문제에 대한 이해를 돕기 위해 아래의 @Nekojimi 답장에 대한 내 의견을 읽으십시오. – user3245573

0

System.out.println("not moving ahead!!!");//program stucked here 라인이 실제로 실행됩니까? 그렇다면 InputStream.read() 함수는 블로킹 함수입니다. 프로그램을 완료 할 수있을 때까지 프로그램 실행을 중단합니다 ("블록"). JavaDoc for InputStream 가입일

:

는 바이트의 배열로 입력 스트림 len 바이트까지의 데이터를 읽는다. len 바이트만큼 읽으려고 시도하지만 더 작은 수를 읽을 수 있습니다. 실제로 읽힌 바이트 수는 정수로 반환됩니다. 이 메서드는 입력 데이터를 사용할 수있을 때까지 파일의 끝이 감지되거나 예외가 throw 될 때까지 실행을 중단합니다. 당신이 예외를 얻고 있지 않기 때문에

, 이것은 당신이) (.read를 호출 할 때, 도착 결코 (이 가능한 데이터를 읽을 수있다, 당신은 프로그램이 데이터를 읽을 기다리고 주위에 앉아 있다는 것을 의미). 클라이언트 프로그램이 실제로 첫 번째 위치에서 데이터를 전송하고 있는지 확인해야합니다.

+0

예, 해당 라인이 실행 중입니다. 사용 가능한 데이터가 없어서 read()에 멈추었을 것입니다. 그러나 클라이언트에서 데이터를 보내고 있습니다 (클라이언트 프로그램을 확인할 수 있음). 그러나 클라이언트가 첫 번째 파일 ("copy.txt"라는 파일이 만들어 지지만 거기에 데이터가 없음)의 데이터를 읽지 못하고 있다고 생각합니다. 따라서 클라이언트가 첫 번째 파일의 읽기 부분을 완료하지 않아 두 번째 파일의 데이터를 보낼 수있는 방법이 없습니다. 그렇다면이 상황을 어떻게 피할 수 있습니까? – user3245573

관련 문제