2011-08-14 7 views
1

code에 파일을 처음 보내면 (전송중인 파일과 상관없이) 코드가 제대로 작동합니다. 그러나 FileSender를 루프로 보내서 파일을 하나씩 보내면 첫 번째 전송 후 수신자 측에서받은 데이터는 임의적입니다 (디버깅 중에 선택하면). 파일을 수신하지도 않습니다. 여기 내가 한 변화와 효과가없는 것입니다.소켓 파일 전송

FileSender.java

import java.io.OutputStream; 
import java.io.File; 
import java.net.Socket; 
public class FileSender { 
public void main(Socket socket,String[] args) { 
try { 

    OutputStream os  = socket.getOutputStream(); 
    int cnt_files = args.length; 

    // How many files? 
    ByteStream.toStream(os, cnt_files); 

    for (int cur_file=0; cur_file<cnt_files; cur_file++) { 
    ByteStream.toStream(os, new File(args[cur_file]).getName()); 
    ByteStream.toStream(os, new File(args[cur_file])); 
    } 
} 
catch (Exception ex) { 
    ex.printStackTrace(); 
} 
} 
} 

문자열 [] 인수의 파일 경로가 전송되도록 포함.

FileReceiver.java

import java.io.File; 
import java.io.InputStream; 
import java.net.Socket; 

public class FileReceiver { 

public void main(Socket socket,String arg) { 
try { 
    InputStream in = socket.getInputStream(); 

    int nof_files = ByteStream.toInt(in); 
System.out.println("reach 1  "+ nof_files); 
    for (int cur_file=0;cur_file < nof_files; cur_file++) { 
    String file_name = ByteStream.toString(in); 

    File file=new File(arg+file_name); 
    System.out.println("Received path is : "+file); 
    ByteStream.toFile(in, file); 
    } 

} 
catch (java.lang.Exception ex) { 
    ex.printStackTrace(System.out); 
} 
} 

} 

인수는 파일이 저장되어야하는 경로가 포함되어 있습니다.

나는 주된 기능을 내가 파일을 전송하려고 할 때마다 언급하고 싶다. 기본적으로 디렉토리를 포함 할 수있는 여러 파일을 전송하려고합니다. 이렇게하려면 다음 코드를 작성했습니다. 내가 틀렸다면

ServerFile.java

import java.io.*; 
import java.net.*; 
public class ClientFile implements Runnable{ 
Socket clientsocket; 
public void run() { 
    try 
    { 
     clientsocket = new Socket("219.64.189.14",6789); 
    // Some code 
    copy(outtoserver,infromserver, files);  // files contains the path of files to be transferred. 
    // Some code 
     clientsocket.close(); 
    } 
    catch(Exception e2) 
    { 
      System.out.println("ClientFile "+String.valueOf(e2) + "\n"); 
    } 
} 
public void copy(DataOutputStream outtoserver,BufferedReader infromserver,String[] files) 
{ 
    try 
    { 
     FileSender fs = new FileSender(); 
     int totalfiles=0; 
     int r=0; 
     File oldfile; 
     outtoserver.write(files.length); 
     String chk; 
     while(totalfiles<files.length) 
     { 

      oldfile = new File(files[totalfiles]); 
      if(oldfile.isDirectory()) 
      { 
       outtoserver.writeBytes("folder\n"); 
       File folder1[] = oldfile.listFiles(); 
       String[] folder = new String[folder1.length]; 
       int count=0; 
       for(File name : folder1) 
       { 
        folder[count] = name + ""; 
        System.out.println(folder[count]); 
        count++; 
       } 
       outtoserver.writeBytes(oldfile.getName()+"\n"); 
       fs.main(clientsocket, folder); 

      } 
      else if(oldfile.isFile()) 
      { 
       outtoserver.writeBytes("file\n"); 
     chk = infromserver.readLine(); 
       if(chk.equals("send")) 
       { 
        outtoserver.writeBytes(oldfile.getName()+"\n"); 
        String[] folder = new String[]{oldfile.getAbsolutePath()}; 
        fs.main(clientsocket, folder); 
       } 
       totalfiles++; 
       outtoserver.flush(); 

      } 
     } 
    } 
    catch(Exception e) 
    { 
     System.out.println("ClientFile -->> "+e.toString()); 
    } 
} 
} 

ClientFile.java

import java.io.*; 
import java.net.*; 
import javax.swing.*; 
class ServerFile implements Runnable { 
Socket conn; 
public ServerFile(Socket a) 
{ 
    conn = a; 
} 
public void run() { 
    File file1; 
    String clientsen=""; 
    try 
    { // Some code 
     copy(outtoclient,infromclient,file1.getAbsolutePath());  //file1 is the directory to which the file has to stored.  
    // some code 
    }  
    catch(Exception e0) 
    { 
     System.out.println("ServerFile "+String.valueOf(e0)+"\n"+e0.getCause()); 
    } 
}//end main 
public void copy(DataOutputStream outtoclient,BufferedReader infromclient,String basepath) 
{ 
    try 
    { 
     FileReceiver fr = new FileReceiver(); 
     int totfiles = infromclient.read(); 
     int tot=0; 
     File file; 
     String path = null,chk; 
     while(tot<totfiles) 
     { 
      chk = infromclient.readLine(); 
      if(chk.equals("file")) 
      { 
       outtoclient.writeBytes("send\n"); 
       path = infromclient.readLine(); 
       path = basepath+File.separator+path; 
       file=new File(path); 
       fr.main(conn, basepath+File.separator); 
      } 
      else if(chk.equals("folder")) 
      { 
       String name = infromclient.readLine(); 
       name = basepath+File.separator+name; 
       new File(name).mkdir(); 
       fr.main(conn, name+File.separator); 
      } 
      tot++; 
     } 
    } 
    catch(Exception e) 
    { 
     System.out.println("Server file: "+e.toString()); 
    } 
} 

}//end class 

꼭 저를 수정합니다.

도움을 주시면 감사하겠습니다.

+0

'ServerFile.java'와'ClientFile.java'도 컴파일되지 않습니다. 그들의'run()'메소드는 다른 메소드 ('outtoserver','infromserver','files','outtoclient','infromclient')의 변수를 참조합니다. 컴파일중인 _actual_ 코드는 무엇입니까? –

답변

-1

그래서 파일 이름과 파일 내용을 어떻게 구분합니까? 파일 이름과 내용이 포함 된 직렬화 가능 클래스를 만드는 것이 더 좋습니다. 이 경우 ObjectInput/OutputStream을 사용할 수 있습니다. 그렇지 않으면 파일 내용/파일 이름 분리자를 정의하고 Scanner 클래스를 사용하여 파일을 입력 스트림에서 분리해야합니다.

+0

파일 이름은 항상 파일 내용 바로 전에 전송됩니다. '[파일 이름 바이트의 길이 (4 바이트 정수)] [파일 이름 바이트] [파일 내용 바이트의 길이 (4 바이트 정수)] [파일 내용 바이트]'와 같이 보입니다. 'Serializable' 클래스는이 특별한 시나리오에서 과도한 소리처럼 들립니다. –

+0

@ Adam : 어떤 식 으로든 도움을 주시겠습니까 ??? – pankaj

+0

@Audrey : 죄송합니다. 저는'FileSender'와'FileReceiver'를보고있었습니다. 다른 클래스들은 다르게 보입니다 ... –

1

"file\n" 또는 "folder\n" 중 하나를 클라이언트에 보냅니다. 이 문자열을 읽으려면 BufferedReader을 사용하고 있습니다. 해당 클래스의 이름에주의를 기울이십시오 : BufferedReader. BufferedReader에서 readLine()을 호출하면 이상을 적어도 바이트만큼 버퍼링 (읽음)합니다. 그것은 라인을 읽는데 필요한 정확한 바이트 수보다 더 많은 수를으로 읽을 수 있습니다. 예를 들어 BufferedReader의 버퍼 크기가 256이지만 행 ("\n" 포함)은 8 바이트 만 필요하다고 가정합니다. 즉, 버퍼링 된 나머지 248 바이트는 FileReceiver으로 읽히지 않습니다. 그런 다음 4 바이트 정수가 필요하기 때문에 철저히 혼란 스럽지만 실제로 다른 것을 읽습니다.

이 예제에서 이미 사용 된 기술을 활용하는 것이 좋습니다.

ByteStream.toStream(os, "file") 

을 그리고 사용하여 읽기 : 예를 들어, 사용 "file"을 보내

ByteStream.toString(in) 
+0

하지만 첫 번째 파일이 어떻게 완벽하게 전송되는지 ... ??? – pankaj