Socketsを使用してクライアント/サーバーチャットを開発しましたが、うまく機能しますが、Deflate圧縮を使用してデータを送信しようとすると、機能しません。出力は「空」です(実際には空ではありませんが、以下で説明します)。 )。
圧縮/解凍部分は100%動作しているので(私はすでにテスト済みです)、問題は送信/受信部分の他の場所にあるはずです。
次の方法を使用して、クライアントからサーバーにメッセージを送信します。
// streamOut is an instance of DataOutputStream
// message is a String
if (zip) { // zip is a boolean variable: true means that compression is active
streamOut.write(Zip.compress(message)); // Zip.compress(String) returns a byte[] array of the compressed "message"
} else {
// if compression isn't active, the client sends the not compressed message to the server (and this works great)
streamOut.writeUTF(message);
}
streamOut.flush();
そして、私はこれらの他の方法を使用してクライアントからサーバーへのメッセージを受け取ります:
// streamIn is an instace of DataInputStream
if (server.zip) { // same as before: true = compression is active
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[512];
int n;
while ((n = streamIn.read(buf)) > 0) {
bos.write(buf, 0, n);
}
byte[] output = bos.toByteArray();
System.out.println("output: " + Zip.decompress(output)); // Zip.decompress(byte[]) returns a String of decompressed byte[] array received
} else {
System.out.println("output: " + streamIn.readUTF()); // this works great
}
プログラムを少しデバッグすると、whileループが終了しないことがわかりました。
byte[] output = bos.toByteArray();
System.out.println("output: " + Zip.decompress(output));
呼び出されることはありません。
これらの2行のコードをwhileループ(bos.write()の後)に入れると、すべて正常に機能します(クライアントから送信されたメッセージが出力されます)。しかし、受信したbyte []配列のサイズが異なる可能性があるため、これが解決策ではないと思います。このため、問題は受信部分にあると思いました(クライアントは実際にデータを送信できます)。
そのため、私の問題は受信部分のwhileループになりました。私は試してみました:
while ((n = streamIn.read(buf)) != -1) {
条件が!= 0の場合でも、以前と同じです。ループが終了することはないため、出力部分が呼び出されることはありません。