2012-05-01 5 views
-1

나는 자바의 소켓을 통해 바이트 배열을 전송하는 애플리케이션을 작성하고있다.소켓에서 바이트 배열을 읽을 수 없다

다음 클라이언트 단에서 바이트 배열의 생성은 : 서버 측

String vote = br.readLine(); 
// the data that i now encrypt using RSA 

      PublicKey pubKey = readKeyFromFilepublic("alicepublic.txt"); 
      Cipher cvote = Cipher.getInstance("RSA"); 
      cvote.init(Cipher.ENCRYPT_MODE, pubKey); 
      byte[] voted = cvote.doFinal(vote.getBytes()); 
      System.out.println(voted); 
      out.println(voted.length); 
      dos.write(voted,0,voted.length); // here i am sending the array to the server 

i는 I가 파일에 기록하여 암호화 및 암호 해독 처리를 체크인

String clen = in.readLine(); // read the length 
byte[] array = new byte[Integer.parseInt(clen)]; // create the array of that length 
dist.readFully(array); // read the array 

// i am unable to read the array here at all ! 

PrivateKey priKey = readKeyFromFileprivate("aliceprivate.txt"); 
Cipher vote = Cipher.getInstance("RSA"); 
vote.init(Cipher.DECRYPT_MODE, priKey); 
byte[] voteData = vote.doFinal(array); 
System.out.println(voteData); 

// finally print the decrypted array 

쓰기 제대로 작동합니다.

저는 양쪽에서 DataInput 및 DataOutput 스트림을 사용하고 있습니다.

내 코드가 잘못되었다는 것을 알려주실 수 있습니까?

+0

예외는 무엇입니까? 오류? 스택 트레이스? – beny23

+0

예외는 발생하지 않고 소켓에서 바이트 배열을 읽으려고 계속 대기합니다. –

답변

2

문자 데이터와 이진 데이터를 같은 스트림 (적어도 다른 스트림이 아닌)에서 혼합하지 마십시오. 당신은 "in"의 타입을 보여주지 않았지만, 그것이 BufferedReader (여기서 핵심 포인트는 "buffered")라고 추측합니다. BufferedReader는 다음 줄보다 이상 읽습니다. 따라서 byte []의 일부가 BufferedReader에 저장됩니다. 스트림상의 모든 조작에 대해서 같은 DataOutputStream/DataInputStream를 사용합니다. 텍스트 데이터를 써야하는 경우 writeUTF/readUTF를 사용하십시오. byte []의 길이를 쓸 때 writeInt/readInt를 사용하면된다.

+0

감사합니다. 전체 코드를 다시 작성하고 하나의 스트림 만 사용했습니다. 지금 매력처럼 작동합니다! 많은 도움이 된 –