2011-10-08 11 views
3

이미지 및 비디오와 같은 파일을 전송하기 위해 java에서 서버 소켓 개념을 사용했습니다. 하지만 클라이언트 측에서는 파일 이름을 사용자 지정합니다. 원래 파일 이름을 그대로 사용할 수 있습니까?서버 소켓 파일 전송

예를 들어

:

전송을위한 서버 측에서 파일이 "abc.txt"인 경우에, 나는 (별도의 이름을 거치지 않고) 클라이언트 측에 반영하기 위해이 같은 이름이 필요합니다. 클라이언트 결국

public class FileServer { 
    public static void main (String [] args) throws Exception { 
    // create socket 
    ServerSocket servsock = new ServerSocket(13267); 
    while (true) { 
     System.out.println("Waiting..."); 

     Socket sock = servsock.accept(); 
     System.out.println("Accepted connection : " + sock); 
     OutputStream os = sock.getOutputStream(); 
    new FileServer().send(os); 
     sock.close(); 
     } 
    } 

    public void send(OutputStream os) throws Exception{ 
     // sendfile 
     File myFile = new File ("C:\\User\\Documents\\abc.png"); 
     byte [] mybytearray = new byte [(int)myFile.length()+1]; 
     FileInputStream fis = new FileInputStream(myFile); 
     BufferedInputStream bis = new BufferedInputStream(fis); 
     bis.read(mybytearray,0,mybytearray.length); 
     System.out.println("Sending..."); 
     os.write(mybytearray,0,mybytearray.length); 
     os.flush(); 
    } 
} 

: 서버 측에서

public class FileClient{ 
    public static void main (String [] args) throws Exception { 


    long start = System.currentTimeMillis(); 


    // localhost for testing 
    Socket sock = new Socket("127.0.0.1",13267); 
    System.out.println("Connecting..."); 
    InputStream is = sock.getInputStream(); 
    // receive file 
    new FileClient().receiveFile(is); 
     long end = System.currentTimeMillis(); 
    System.out.println(end-start); 

    sock.close(); 
    } 

    public void receiveFile(InputStream is) throws Exception{ 
     int filesize=6022386; 
     int bytesRead; 
     int current = 0; 
     byte [] mybytearray = new byte [filesize]; 

     FileOutputStream fos = new FileOutputStream("def"); 
     BufferedOutputStream bos = new BufferedOutputStream(fos); 
     bytesRead = is.read(mybytearray,0,mybytearray.length); 
     current = bytesRead; 


     do { 
      bytesRead = 
       is.read(mybytearray, current, (mybytearray.length-current)); 
      if(bytesRead >= 0) current += bytesRead; 
     } while(bytesRead > -1); 

     bos.write(mybytearray, 0 , current); 
     bos.flush(); 
     bos.close(); 
    } 
} 

답변

2

예, 실제 파일 내용 앞에 메타 데이터 (사례 myFile.getName())를 전송하고 클라이언트와 서버를 읽고 해당 메타 데이터를 방출합니다. 기존 프로토콜 (예 : HTTP)과 Content-Disposition (헤더)을 사용하는 것이 좋습니다.

+0

하지만 그 일은 클라이언트에 파일 배열을 보내는 것입니다. 파일의 이름을 파일의 바이트 배열에 추가 할 수 없습니까? 그렇다면 어떻게하는지 알려주십시오. – Arun

+0

@Arun 물론 가능합니다. 프로토콜을 고안하면됩니다. 어떤 직렬화 방법/프로토콜을 사용하고 있습니까? 질문에 실제로 파일을 보내거나받는 코드 (<15 줄)를 포함하면 큰 도움이됩니다. – phihag

+0

전체 소스 코드로 내 질문을 편집했습니다. 이것은 실제로이 질문에 게시 된 링크에서 가져온 것입니다. 친절하게 도와주세요. 늦은 답변 죄송합니다. – Arun

4

는 다음 중 하나

는 는

A)는

B, 그것을 요구하기 때문에이 이름을 알고 가정합니다) 서버로 먼저 이름을 보낸다 스트림의 일부.

실제로 정보를 보내지 않고 정보를 보내는 방법을 발명 한 경우 알려 주시면 억만 장자가 될 수 있습니다. 우리는 이것을 '컴퓨터 텔레파시'라고 부를 수 있습니다.

+0

파일을 클라이언트에 바이트 배열로 보냅니다. 한가지는 temme ... 파일의 이름을 포함 할 것인가 말 것인가? – Arun

+0

이름을 보내면 이름이 포함됩니다. 그렇지 않으면 파일에 자체 이름이 포함되지 않을 수 있습니다. –

1

이렇게하는 더 쉬운 방법이 있습니다. DataInputStream 내에 입력 스트림을 랩하고 .writeUTF (myFile.getName())와 같은 메소드를 사용하십시오. 마찬가지로, DataInputStream에 .readUTF를 적용하여 수신자에서 파일 이름을 읽을 수 있습니다. 다음은 샘플 코드는 다음과 같습니다 보낸 사람 :

FileInputStream fis = new FileInputStream(myFile); 
    BufferedInputStream bis = new BufferedInputStream(fis); 
    DataInputStream dis = new DataInputStream(bis); 
    OutputStream os; 
    try { 
     os = socket.getOutputStream(); 
     DataOutputStream dos = new DataOutputStream(os); 
     dos.writeUTF(myFile.getName()); 
.............////// catch exceptions 

수신기 :

InputStream in; 
    try { 
     bufferSize=socket.getReceiveBufferSize(); 
     in=socket.getInputStream(); 
     DataInputStream clientData = new DataInputStream(in); 
     String fileName = clientData.readUTF(); 
     System.out.println(fileName); 
................../////// catch exceptions