0
private void readIncomingMessage() {
    try {
        StringBuilder builder = new StringBuilder();
        InputStream is = socket.getInputStream();
        int length = 1024;
        byte[] array = new byte[length];
        int n = 0;

        while ((n = is.read(array, n, 100)) != -1) {
            builder.append(new String(array));

            if (checkIfComplete(builder.toString())) {
                buildListItems(builder.toString(), null);
                builder = new StringBuilder();
            }
        }

    } catch (IOException e) {
        Log.e("TCPclient", "Something went wrong while reading the socket");
    }
}

やあ、

100バイトのブロックごとにストリームを読み取り、それらのバイトを文字列に変換して、その文字列が特定の条件に適合するかどうかを確認したいと思います。

しかし、デバッグすると、ビルダーのカウントが3072であることがわかり ます
。また、(text 、、、、、、、、、、、、、 text 、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
文字列ビルダーへのテキスト?

どうも :)

 private void readIncomingMessage() {
    try {
        StringBuilder builder = new StringBuilder();
        InputStream is = socket.getInputStream();
        int length = 100;
        byte[] array = new byte[length];
        int n = 0;

        while ((n = is.read(array, 0, length)) != -1) {
            builder.append(new String(array, 0, n));

            if (checkIfComplete(builder.toString())) {
                buildListItems(builder.toString(), null);
                builder = new StringBuilder();
            }
        }

    } catch (IOException e) {
        Log.e("TCPclient", "Something went wrong while reading the socket");
    }
}

この解決策は私のためにトリックをしました。このソリューションの欠点はありますか?

4

2 に答える 2

2

2つの問題:

  1. 'n'バイトを文字列に変換するときに値を使用する必要があります。具体的には、このStringコンストラクターを使用しますString(byte[] bytes, int offset, int length)
  2. あなたがしているように、バイトを任意の境界で文字列に変換するとき、マルチバイト文字を破壊する可能性があります。とそこから文字を読むInputStreamReader場合は、上に置く方が良いでしょう。'is'
于 2012-07-12T14:59:54.680 に答える
1

詳細については、、およびのドキュメントをお読みread(byte[], int, int)くださいnew String(byte[])new String(byte[], int, int)

nは、最後に読み取られたバイト数を保持します。読み取られたバイトの総数ではありません。一度に最大100バイトを読み取りたい場合は、サイズ1024のバイト配列は必要ありません。100で十分です。バイト配列から文字列を作成する場合、配列のどの部分を使用するかを指定しない限り、配列全体が使用されます(読み取りによって半分しか埋められなかった場合でも)。このようなものは機能するはずですが、まだ改善できる点があります。

private void readIncomingMessage() {
  try {
    StringBuilder builder = new StringBuilder();
    InputStream is = socket.getInputStream();
    int length = 100;
    byte[] array = new byte[length];
    int pos = 0;
    int n = 0;

    while (pos != length && ((n = is.read(array, pos, length-pos)) != -1)) {
        builder.append(new String(array, pos, n));
        pos += n;
        if (checkIfComplete(builder.toString())) {
            buildListItems(builder.toString(), null);
            builder = new StringBuilder();
            pos = 0;
        }
    }

} catch (IOException e) {
    Log.e("TCPclient", "Something went wrong while reading the socket");
}

}

于 2012-07-12T15:08:47.977 に答える