从服务器读取byte []

时间:2012-04-27 02:48:07

标签: java datainputstream

我正在尝试阅读从客户端发送到服务器的byte[]

这是我的客户代码......

 din = new DataInputStream(socket.getInputStream());
 dout = new DataOutputStream(socket.getOutputStream());

 Cipher cipher = Cipher.getInstance("RSA"); 
 // encrypt the aeskey using the public key 
 cipher.init(Cipher.ENCRYPT_MODE, pk);

 byte[] cipherText = cipher.doFinal(aesKey.getEncoded());
 dout.write(cipherText);

这是我的服务器代码......

 DataInputStream dis = new DataInputStream(socket.getInputStream());          
 DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

 String chiper = dis.readUTF();
 System.out.println(chiper);

但是,dis.readUTF();行失败并出现异常...

java.io.EOFException at java.io.DataInputStream.readFully(DataInputStream.java:197)
    at java.io.DataInputStream.readUTF(DataInputStream.java:609)
    at java.io.DataInputStream.readUTF(DataInputStream.java:564)
    at gameserver.ClientHandler.run(GameServer.java:65)

有人可以帮助我理解为什么这不起作用。

4 个答案:

答案 0 :(得分:4)

对于初学者来说,如果你在一端编写一系列(加密!)字节,并试图在另一端读取一个UTF格式的字符串......你将会遇到不好的时间。

我建议你在客户端做一些像

这样的事情
dout.writeInt(cipherText.length);
dout.write(cipherText);

然后在服务器端你应该做类似

的事情
int byteLength = dis.readInt(); // now I know how many bytes to read
byte[] theBytes = new byte[byteLength];
dis.readFully(theBytes);

答案 1 :(得分:0)

DataIputStream.readUTF()用于使用DataOutputStream.writeUTF()编写的数据。你还没有写过UTF,所以你无法阅读它。

这是二进制数据,所以你根本不应该考虑UTF或字符串。用writeInt()写出数组的长度,然后用write()写出数组的长度。在另一端,用readInt()读取长度,分配一个大的byte []缓冲区,然后用readFully()将密文读入其中。

答案 2 :(得分:0)

哟必须使用read方法获取消息并获取真实消息的字符数,然后将其转换为字符串

int bytesRead = 0;
byte[] messageByte = new byte[1000];

bytesRead = dis.read(messageByte);
String chiper = new String(messageByte, 0, bytesRead);
System.out.println(chiper);

答案 3 :(得分:-1)

在客户端,你应该将byte []数组转换为String并使用 dout.writeUTF()发送转换后的字符串。

相关问题