我在服務器端接收數據時遇到一些麻煩。這裏有雲代碼:客戶端部分使用BufferedInputStream在服務器端接收數據
我有:
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)。爲什麼發生這種情況?
「...作爲一個額外的便利,它試圖通過反覆調用底層流的讀取方法儘可能多地讀取字節......」表單:http://docs.oracle.com/javase /1.4.2/docs/api/java/io/BufferedInputStream.html – savionok 2012-03-29 13:03:17