2012-05-01 71 views
-1

我在写一个应用程序,我在java中通过套接字传输字节数组。无法从套接字读取字节数组

字节数组的在客户端生成如下:

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 

在服务器侧我写

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(这里的关键点是“缓冲”)。 BufferedReader将读取更多比下一行,所以你的byte []的一部分坐在你的BufferedReader。对流上的所有操作使用相同的DataOutputStream/DataInputStream。如果您需要编写文本数据,请使用writeUTF/readUTF。当你写入byte []的长度时,只需使用writeInt/readInt。

+0

谢谢,重写了整个代码并只使用了一个流!现在就像魅力一样!这帮助了很多 –