UWP c# 从 StreamSocket 读取 XML

UWP c# read XML from StreamSocket

我正在尝试通过 TCP 网络套接字 (StreamSocket) 与 XMPP (Jabber) 服务器通信,我正在使用以下代码来读取服务器发送给我的内容:

StreamSocket tcpSocket;
StreamReader reader;
int BUFFER_SIZE = 4096;

// Connecting to a remote XMPP server ....

reader = new StreamReader(tcpSocket.InputStream.AsStreamForRead());
string result;
while (true)
{
    result = "";
    while (true)
    {
        char[] buffer = new char[BUFFER_SIZE];
        await reader.ReadAsync(buffer, 0, BUFFER_SIZE);
        string data = new string(buffer);

        // Detecting if all elements in the buffer array got replaced => there is more to read
        if (data.IndexOf("[=11=]") >= 0 || reader.EndOfStream)
        {
            result + data.Substring(0, data.IndexOf("[=11=]"));
            break;
        }
        result += data;
    }   
    Debug.WriteLine(result);
}

我的代码适用于长度小于 4096 个字符的字符串,但一旦字符串超过 4096 个字符,它就会失败(不会检测到消息结束)。它一直等到它收到一个 < 4096 个字符的新字符串,将两个字符串连接起来 returns 它们作为一个字符串。

有没有办法获取字符串的实际长度并依次读取?

您已将 4096 设置为 BUFFER_SIZE 并且它被设置为 StreamReader.ReadAsync 和 char 数组中的计数参数。当字符串包含超过 4096 个字符时,它将失败。

你应该可以得到流中的实际长度,我们可以使用Stream.Length来得到流的字节长度。 Array 的最后一个字符是“\0”。当您创建 char 数组时,您应该能够将 Stream.Length 加一设置为 char 数组。

例如:

StreamSocket socket;
StreamSocket tcpSocket;
StreamReader reader;

reader = new StreamReader(tcpSocket.InputStream.AsStreamForRead());
var  BUFFER_SIZE=(int)(tcpSocket.InputStream.AsStreamForRead()).Length;
string result;
while (true)
{
    result = "";
    while (true)
    {
        char[] buffer = new char[BUFFER_SIZE+1];
        await reader.ReadAsync(buffer, 0, BUFFER_SIZE);
        string data = new string(buffer);
        if (data.IndexOf("[=10=]") >= 0 || reader.EndOfStream)
        {
            result = data.Substring(0, data.IndexOf("[=10=]"));
            break;
        }
        result += data;
    }
    Debug.WriteLine(result);
}

如果要读取从当前位置到流末尾的所有字符,可以使用StreamReader.ReadToEndStreamReader.ReadToEndAsync方法。

我终于想出了阅读长消息的方法: 我必须使用 DataReaderDataWriter 而不是 StreamReaderStreamWriter.

/// <summary>
/// How many characters should get read at once max.
/// </summary>
private static readonly int BUFFER_SIZE = 4096;

private StreamSocket socket;
private DataReader dataReader;
private DataWriter dataWriter;

public string readNextString() {
    string result = "";
    readingCTS = new CancellationTokenSource();

    try {
        uint readCount = 0;

        // Read the first batch:
        Task < uint > t = dataReader.LoadAsync(BUFFER_SIZE).AsTask();
        t.Wait(readingCTS.Token);
        readCount = t.Result;

        if (dataReader == null) {
            return result;
        }

        while (dataReader.UnconsumedBufferLength > 0) {
            result +=dataReader.ReadString(dataReader.UnconsumedBufferLength);
        }

        // If there is still data left to read, continue until a timeout occurs or a close got requested:
        while (!readingCTS.IsCancellationRequested && readCount >= BUFFER_SIZE) {
            t = dataReader.LoadAsync(BUFFER_SIZE).AsTask();
            t.Wait(100, readingCTS.Token);
            readCount = t.Result;
            while (dataReader.UnconsumedBufferLength > 0) {
                result += dataReader.ReadString(dataReader.UnconsumedBufferLength);
            }
        }
    }
    catch(AggregateException) {}
    catch(NullReferenceException) {}

    return result;
}