【问题标题】:UWP c# read XML from StreamSocketUWP c# 从 StreamSocket 读取 XML
【发布时间】:2017-10-10 16:45:56
【问题描述】:

我正在尝试通过 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("\0") >= 0 || reader.EndOfStream)
        {
            result + data.Substring(0, data.IndexOf("\0"));
            break;
        }
        result += data;
    }   
    Debug.WriteLine(result);
}

我的代码适用于长度

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

【问题讨论】:

    标签: c# sockets uwp xmpp


    【解决方案1】:

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

    你应该可以得到 Stream 中的实际长度,我们可以使用Stream.Length 来获取 Stream 的字节长度。 Array 的最后一个字符是“\0”。当您创建 char 数组时,您应该能够将 Stream.Length 加 1 设置为 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("\0") >= 0 || reader.EndOfStream)
            {
                result = data.Substring(0, data.IndexOf("\0"));
                break;
            }
            result += data;
        }
        Debug.WriteLine(result);
    }
    

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

    【讨论】:

    • 感谢您的帮助,但如果我使用 BUFFER_SIZE=(int)(tcpSocket.InputStream.AsStreamForRead()).Length;,我会收到 System.NotSupportedException:此流不支持 Length 属性,因为它不可搜索。如果我使用 await reader.readToEndAsync() 它不会返回任何东西 - 它只会等待
    • 能不能通过tcpSocket.InputStream.AsStreamForRead()方法获取流?
    • 是的,它返回一个流对象,但是Length对象对于它返回的这种流是不可用的。
    【解决方案2】:

    我终于想通了阅读长消息: 我必须使用 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多