2015-02-02 2 views
0

Java 클래스 용으로 프로젝트를 만들고 소켓을 사용 중입니다. 온라인 튜토리얼을보고 도움을 받겠습니다. pdf 형식의 서버에 파일을 저장 한 다음 CLient가 Sever에서이 파일을 요청할 수있게합니다.파일 전송하지만 해당 Launcher (Adobe PDF)에로드 할 수 없음 - Java 서버 클라이언트

내 문제 파일을 요청했지만 파일을 요청한 후 클라이언트 컴퓨터에 저장하려고하면 파일을 실행해야합니다. 어도비는 "Adobe에서 파일을 열 수 없습니다. 파일 형식이 지원되지 않습니다. 되어 손상 여기

로 파일은 어떤 사람이 나를 도와 수 있다면 감사하겠습니다 제발 내 코드입니다 :

서버 코드 :

import java.io.*; 
import java.net.*; 

public class SimpleFileServer { 

public final static String FILE_TO_SEND = "‪c:/Users/Acer/Downloads/COAFlags.pdf"; // you may change this 

public static void main(String args[]) { 

    while (true) { 
     ServerSocket welcomeSocket = null; 
     Socket connectionSocket = null; 
     BufferedOutputStream outToClient = null; 

     try { 
      welcomeSocket = new ServerSocket(3248); 
      connectionSocket = welcomeSocket.accept(); 
      outToClient = new BufferedOutputStream(connectionSocket.getOutputStream()); 
     } catch (IOException ex) { 
      // Do exception handling 
     } 

     if (outToClient != null) { 
      File myFile = new File(FILE_TO_SEND); 
      byte[] mybytearray = new byte[(int)myFile.length()]; 

      FileInputStream fis = null; 

      try { 
       fis = new FileInputStream(myFile); 
      } catch (FileNotFoundException ex) { 
       // Do exception handling 
      } 
      BufferedInputStream bis = new BufferedInputStream(fis); 

      try { 
       bis.read(mybytearray, 0, mybytearray.length); 
       outToClient.write(mybytearray, 0, mybytearray.length); 
       outToClient.flush(); 
       outToClient.close(); 
       connectionSocket.close(); 

       // File sent, exit the main method 
       return; 
      } catch (IOException ex) { 
       // Do exception handling 
      } 
     } 
    } 
}} 

클라이언트

import java.io.*; 
import java.io.ByteArrayOutputStream; 
import java.net.*; 

public class SimpleFileClient { 

private final static String serverIP = "localhost"; 
public final static int FILE_SIZE = 55000; 
private final static int serverPort = 3248; 
private final static String fileOutput = "c:/Users/Acer/Downloads/sourcedownloaded.pdf"; 

public static void main(String args[]) { 
    byte[] aByte = new byte[FILE_SIZE]; 
    int bytesRead; 

    Socket clientSocket = null; 
    InputStream is = null; 

    try { 
     clientSocket = new Socket(serverIP , serverPort); 
     is = clientSocket.getInputStream(); 
    } catch (IOException ex) { 
     // Do exception handling 
    } 

    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

    if (is != null) { 

     FileOutputStream fos = null; 
     BufferedOutputStream bos = null; 
     try { 
      fos = new FileOutputStream(fileOutput); 
      bos = new BufferedOutputStream(fos); 
      bytesRead = is.read(aByte, 0, aByte.length); 

      do { 
        baos.write(aByte); 
        bytesRead = is.read(aByte); 
      } while (bytesRead != -1); 

      bos.write(baos.toByteArray()); 
      bos.flush(); 
      bos.close(); 
      clientSocket.close(); 
     } catch (IOException ex) { 
      // Do exception handling 
     } 
    } 
}} 

전송하려는 파일이 54KB이므로 괜찮습니다. 범위를 벗어났습니다.

+0

일반적인 문제. 전체 파일을 메모리에 저장하려고 시도한'read(); '에 의해 반환 된 길이를 무시합니다. 무의미한 ByteArrayOutputStream;의 사용 ... – EJP

+0

byteArrayOutPutStream이 쓸모 없다면 무엇을 사용해야합니까? – Redcode

+0

나는 그것이 쓸모 없다고 말하지 않았습니다. 나는 당신이 그것을 무의미하게 사용하고 있다고 말했다. 'ByteArrayOutputStream'에 쓰는 것은 모두'FileOutputStream'에 직접 쓸 수 있습니다. 당신이하고있는 방식은 단지 공간을 낭비하고 대기 시간을 추가합니다. 또한 do/while 패턴은 올바르지 않습니다. 입력이 비어 있으면 정크 메일을 쓰게됩니다. 사실, 코드는 대부분 정크를 씁니다. @ farukdgn의 대답은 올바른 방법을 찾아보십시오. – EJP

답변

1

이것은 사용자가 수행하는 방식이 아닙니다. while 루프 안에서 파일을 전송해야하므로 사용하는 버퍼가 많은 메모리를 사용하지 않게됩니다. 서버 측 :

ServerSocket socket = new ServerSocket(); 
socket.bind(new InetSocketAddress("127.0.0.1",9200)); 
while(true) //that loop provides server non-stop sending, it will response to client requests till you terminate the application. 
{ 
    Socket received = socket.accept(); 
    FileInputStream input = new FileInputStream("c:/Users/Acer/Downloads/COAFlags.pdf"); 
    OutputStream output = received.getOutputStream(); 
    int length; 
    byte[] buffer = new byte[4096]; 

    while((length = input.read(buffer)) != -1) 
    { 
     output.write(buffer, 0, length); 
    } 

    output.close(); //no need to flush because close() already does it 
    input.close(); 
} 

클라이언트 측 :

Socket socket = new Socket("127.0.0.1", 9200); 
InputStream input = socket.getInputStream(); 
FileOutputStream output = new FileOutputStream("c:/Users/Acer/Desktop/abc.pdf"); 
int length; 
byte[] buffer = new byte[4096]; 

while((length = input.read(buffer)) != -1) 
{ 
    output.write(buffer, 0, length); 
} 

output.close(); 
input.close(); 

참고 : 버퍼 크기는 선택 사항입니다. 4096이 일반적으로 사용됩니다.

+0

알았어, 지금 해보고 돌아 가자. – Redcode

+0

알았어. 내가 말한 추가 코드로 편집했는데 잘못된 코드를 추가했는지 말해 줄 수 없다. – Redcode

+0

전체 코드를 추가 했으므로 붙여 넣기를 복사하고 시도한 다음 분석 할 수 있습니다. – farukdgn

0

새 서버 코드 :
import java.io. ; import java.net.;

공용 클래스 SimpleFileServer {

public final static String FILE_TO_SEND = "‪c:/Users/Acer/Downloads/COAFlags.pdf"; // you may change this 

public static void main(String args[]) { 

    while (true) { 
     ServerSocket welcomeSocket = null; 
     Socket connectionSocket = null; 
     OutputStream output = null; 

     try { 
      welcomeSocket = new ServerSocket(3248); 
      connectionSocket = welcomeSocket.accept(); 
      output = connectionSocket.getOutputStream(); 
     } catch (IOException ex) { 
      // Do exception handling 
     } 

     if (output != null) { 



      try { 
       int length; 
       byte[] buffer = new byte[4096]; 
       FileInputStream input = new FileInputStream(FILE_TO_SEND); 
       try { 
        while((length = input.read(buffer)) != -1) 
        { 
         output.write(buffer, 0, length); 
        } 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

       try { 
        output.close(); 
        input.close(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } //no need to flush because close() already does it 

      } catch (FileNotFoundException ex) { 
       // Do exception handling 
      } 



     } 
    } 
}} 

업데이트 클라이언트

가져 오기는 java.io ; import java.net.;

공용 클래스 SimpleFileClient {

private final static String serverIP = "localhost"; 
public final static int FILE_SIZE = 55000; 
private final static int serverPort = 3248; 
private final static String fileOutput = "c:/Users/Acer/Downloads/sourcedownloaded.pdf"; 

public static void main(String args[]) { 
    byte[] buffer = new byte[55000]; 
    int length; 

    Socket clientSocket = null; 
    InputStream input = null; 

    try { 
     clientSocket = new Socket(serverIP , serverPort); 
     input = clientSocket.getInputStream(); 
    } catch (IOException ex) { 
     // Do exception handling 
    } 

    // ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

    if (input != null) { 


     FileOutputStream output = null; 
     //BufferedOutputStream bos = null; 
     try { 
      output = new FileOutputStream(fileOutput); 
      while((length = input.read(buffer)) != -1) 
      { 
       output.write(buffer, 0, length); 
      } 

      output.close(); 
      input.close(); 
     } catch (IOException ex) { 
      // Do exception handling 
     } 
    } 
}} 
+0

이것은 @farukdgn 위의 코드입니다 – Redcode

관련 문제