サーバー側でデータを受信する際にいくつか問題があります。ここでは、コードになります。クライアント側で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());
結果として、サーバー側では最初のデータのみが正しく受信され、2番目のデータは空(0)です。なぜこれが起こるのですか?
"...便利な点として、基になるストリームのreadメソッドを繰り返し呼び出すことで、できるだけ多くのバイトを読み込もうとしています...." form here:http://docs.oracle.com/javase /1.4.2/docs/api/java/io/BufferedInputStream.html – savionok