我在服务器端接收数据时遇到了一些麻烦。这是代码:
在客户端部分我有:
public void sendMessage(byte[] bytes) throws IOException {
byte[] lenghtInBytes = ByteBuffer.allocate(4).putInt(bytes.length).array();
out.write(lenghtInBytes,0,4);
out.write(bytes,0,bytes.length);
out.flush();
}
在服务器部分我有功能:
public byte[] receiveMessage() throws IOException, ClassNotFoundException {
byte[] lenghtInBytes = new byte[4];
in.read(lenghtInBytes,0,4);
int length = ByteBuffer.wrap(lenghtInBytes).getInt();
serverLogger.debug(length);
byte[] data = new byte[length];
in.read(data,0, length);
serverLogger.debug(new String(data));
return data;
}
服务器主页中的:
out = new BufferedOutputStream(sslClientSocket.getOutputStream());
out.flush();
in = new BufferedInputStream(sslClientSocket.getInputStream());
System.out.println(new String(receiveString()));
System.out.println(new String(receiveString()));
在客户端主页:
sendMessage(firstData.getBytes());
sendMessage(secondData.getBytes());
因此在服务器端我只能正确接收firstdata,而secondData为空(为0)。为什么会这样?
答案 0 :(得分:0)
BufferedInputStream.read(byte [] b,int off,int len)只读取可用字节。要读取所有字节,必须在循环中包装in.read()。
答案 1 :(得分:0)
问题是由于服务器端使用了jre6,而客户端应用程序在jre7上运行。