2013-05-09 2 views
0

클라이언트가 보낸 데이터를 저장하는 파일을 서버가 유지하도록하려는이 클라이언트 - 서버 프로그래밍이 필요합니다. 다음과 같이 코드는 다음과 같습니다파일 관리 클라이언트 - 서버 프로그래밍

클라이언트 측 :

public class ClientSide { 
    public static void main(String[] argv) throws Exception { 

     String sentence; 
     BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); 
     Socket clientSocket = new Socket("localhost", 6789); 
     DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); 
     sentence = inFromUser.readLine(); 
     outToServer.writeBytes(sentence + '\n');    
     clientSocket.close(); 
} 
} 

서버 측 :

public class ServerSide { 
    public static void main(String[] args) throws IOException { 
      File file=new File("s1.txt"); 
      ServerSocket servsock = new ServerSocket(6789); 

      Socket sock = servsock.accept(); 
      byte[] mybytearray = new byte[1024]; 
      InputStream is = sock.getInputStream(); 
      FileOutputStream fos = new FileOutputStream(file,true); 
      BufferedOutputStream bos = new BufferedOutputStream(fos); 

      int bytesRead = is.read(mybytearray, 0, mybytearray.length); 
      bos.write(mybytearray, 0, bytesRead); 

      bos.close(); 
      sock.close(); 

      BufferedReader write=new BufferedReader(new FileReader(file)); 
      String line; 
      while((line=write.readLine())!=null) { 
       System.out.println(line); 
      } 

    } 
} 

이제이며 사용자가 'Vinayak'예를 들어, 서버에 데이터를 보내는으로 데이터가 서버로 전송되면 첫 번째 문자 'V'만 파일에 기록됩니다. 나는 코드에서 뭔가를 놓치고 있어야하고 나는 그것을 발견 할 수 없다. 또한 비슷한 질문을했습니다. here 그러나 원하는 결과를 얻지 못했습니다.

+0

readsByte를 파일 출력 스트림에 쓰기 전에 입력 스트림에서 flush를 호출 해보십시오. 희망이 도움이됩니다! –

+0

@JunedAhsan 나는 InputStream을 플러시 할 수 없다고 생각한다. –

답변

1

읽기 작업이 실제로 서버 끝에서 원하는만큼 많은 바이트를 읽었는지 확인해야합니다. javadocs for InputStream 참조 :

실제로 읽은 바이트 수는 정수로 반환됩니다. 이 메서드는 입력 데이터를 사용할 수 있거나 파일 끝이 감지되거나 예외가 throw 될 때까지 실행되지 않습니다.

...

읽기 (b는, 오프 렌) InputStream 클래스의 방법은 단순히()를 반복해서 읽기 메서드를 호출합니다. 최초의 호출로 IOException가 발생했을 경우, 그 예외는 read (b, off, len) 메소드의 호출로부터 돌려 주어집니다. 이후의 read()의 호출로 IOException가 발생하면 (자), 예외는 캐치되어 마치 파일의 마지막 인 것처럼 다루어집니다. 그 시점까지 읽힌 바이트는 b에 저장되고 예외 전에 읽은 바이트 수는 루프로 코드를 읽을 서버를 변경

을 반환 발생했습니다 서버에

int bytesRead = -1; 
    while ((bytesRead = is.read(mybytearray, 0, mybytearray.length)) != -1) { 
     System.out.println(bytesRead); 
     bos.write(mybytearray, 0, bytesRead); 
    } 

출력 side :

1 
85 
9 
9 
    ... 
5 
10 
8 
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin fermentum facilisis nulla id aliquet. Suspendisse venenatis condimentum erat adipiscing interdum. Etiam aliquet iaculis mauris lacinia lacinia. Morbi nec nisi est. Duis vel nunc a risus scelerisque feugiat. Morbi eget odio ac arcu vehicula facilisis vel ut nibh. Morbi sodales tristique ante eu aliquam. Ut a leo nisi. Morbi eu purus sed lectus mattis tincidunt. 
+0

또한 "InputStream 클래스의 read (b, off, len) 메서드는 단순히 read() 메서드를 반복적으로 호출한다"라고 말합니다. 코드를 디버깅 할 때 읽기만합니다. 첫 번째 문자 즉, bytesRead의 값 = 1 –

+0

답변을 업데이트했습니다. –

+0

감사합니다. 어리석은 실수였습니다. –

관련 문제