C# 从StreamSocketListener读取数据-Upnp订阅事件

C# 从StreamSocketListener读取数据-Upnp订阅事件,c#,uwp,win-universal-app,C#,Uwp,Win Universal App,我在从StreamSocketListener读取数据时遇到问题,这让我抓狂。。。我收到了好的和坏的结果,我不明白为什么会发生这种情况。好与坏意味着:完整与不完整的结果: 非常感谢您的建议或指导。我已经试了几天了 方法创建和启动StreamSocketListener: public async Task StartListening() { socketListener = new StreamSocketListener(); socketLi

我在从StreamSocketListener读取数据时遇到问题,这让我抓狂。。。我收到了好的和坏的结果,我不明白为什么会发生这种情况。好与坏意味着:完整与不完整的结果:

非常感谢您的建议或指导。我已经试了几天了

方法创建和启动StreamSocketListener:

    public async Task StartListening()
    {
        socketListener = new StreamSocketListener();
        socketListener.ConnectionReceived += onConnectionReceived;
        socketListener.Control.KeepAlive = false;

        await socketListener.BindEndpointAsync("localHostName", "Port");
     }
触发事件:

    private async void onConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
    {
        StringBuilder request = new StringBuilder();
        using (IInputStream input = args.Socket.InputStream)
        {
            byte[] data = new byte[8192];
            IBuffer buffer = data.AsBuffer();
            uint dataRead = 8192;
            while (dataRead == 8192)
            {
                await input.ReadAsync(buffer, 8192, InputStreamOptions.Partial);
                request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
                dataRead = buffer.Length;
            }
        }
        Debug.WriteLine(string.Format("String: {0}", WebUtility.HtmlDecode(request.ToString())));
    }
订阅UpnP事件的方法。它工作正常,我收到通知:

    public async Task Subscribe()
    {
        string HostName = App.SocketListener.Hostname;
        if (string.IsNullOrEmpty(HostName)) { return; }

        Timer = ThreadPoolTimer.CreatePeriodicTimer(async (t) => { await UpdateSubscribe(); }, TimeSpan.FromSeconds(250));

        foreach (var keyvalue in ServiceEvents)
        {
            try
            {
                HttpClient httpClient = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("SUBSCRIBE"), new Uri(keyvalue.Value));
                request.Headers.Add("CALLBACK", "<" + HostName + ">");
                request.Headers.Add("NT", "upnp:event");
                request.Headers.Add("TIMEOUT", "Second-300");

                HttpResponseMessage response = await httpClient.SendRequestAsync(request, HttpCompletionOption.ResponseHeadersRead);

                SubscriberDictionary[(keyvalue.Value, keyvalue.Key, this)] = response.Headers["SID"];
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
    }
我也试过这个。但同样的,它一点也不好用。结果即将出来,或者我正在等待30秒以上以获得一些结果:

private async void onConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
    using (Stream inStream = args.Socket.InputStream.AsStreamForRead())
    {
        using (StreamReader reader = new StreamReader(inStream))
        {
            result = await reader.ReadToEndAsync();
        }
    }
我真的需要你的帮助

我终于想出了这个解决办法。我似乎工作得很好。但有时需要很长时间才能获得所有数据。即使数据不是很大:

    private async Task readingDataFromConnection(StreamSocket socket)
    {
        Dictionary < string, string> result = new Dictionary<string, string>();
        StringBuilder stringBuilder = new StringBuilder();
        using (Stream inStream = socket.InputStream.AsStreamForRead())
        {
            string line;
            using (StreamReader reader = new StreamReader(inStream))
            {
                do
                {
                    line = await reader.ReadLineAsync();
                    string[] stringSeparators = new string[] { ": " };
                    string[] linesplit;

                    linesplit = line.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);

                    if ((linesplit?.Count() ?? 0) == 2) { result[linesplit[0]] = linesplit[1]; }

                } while (!string.IsNullOrEmpty(line));

                if (result.TryGetValue("Content-Length", out string value))
                {
                    if (Int32.TryParse(value, out int length))
                    {
                        char[] buffer = new char[length];
                        int count = length;

                        count = await reader.ReadBlockAsync(buffer, 0, length);

                        while (count != length)
                        {
                            count += await reader.ReadBlockAsync(buffer, count, length-count);
                        }
                        string data = new string(buffer);
                    }
                }
            }
        }
    }
专用异步任务从连接读取数据(StreamSocket)
{
Dictionaryresult=newdictionary();
StringBuilder StringBuilder=新的StringBuilder();
使用(Stream inStream=socket.InputStream.AsStreamForRead())
{
弦线;
使用(StreamReader=新StreamReader(流内))
{
做
{
line=wait reader.ReadLineAsync();
字符串[]字符串分隔符=新字符串[]{”:“};
字符串[]行拆分;
linesplit=line.Split(StringSeparator、StringSplitOptions.RemoveEmptyEntries);
如果((linesplit?.Count()??0)==2){result[linesplit[0]]=linesplit[1];}
}而(!string.IsNullOrEmpty(line));
if(result.TryGetValue(“内容长度”,输出字符串值))
{
if(Int32.TryParse(值,out int length))
{
字符[]缓冲区=新字符[长度];
int计数=长度;
计数=等待读取器。ReadBlockAsync(缓冲区,0,长度);
while(计数!=长度)
{
count+=等待读取器.ReadBlockAsync(缓冲区、计数、长度计数);
}
字符串数据=新字符串(缓冲区);
}
}
}
}
}

这可能会帮助其他人…

“在调用StreamSocketListener类上的异步方法时,必须编写代码来处理异常。异常可能由参数验证错误、名称解析错误和网络错误导致。网络错误导致的异常(例如,连接中断、连接故障和服务器故障)随时可能发生。“请参考客户的备注。谢谢您的建议。我将更改订单code@JaydenGu-MSFT:也许你可以进一步帮助我。我成功订阅了Upnp事件并收到了消息,但我收到消息的速度非常慢……这不是网络问题。如果我使用其他工具(例如英特尔Upnp开发工具)进行检查回复很快。这让我抓狂…非常感谢您的进一步帮助。。。
private async void onConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
    using (Stream inStream = args.Socket.InputStream.AsStreamForRead())
    {
        using (StreamReader reader = new StreamReader(inStream))
        {
            result = await reader.ReadToEndAsync();
        }
    }
    private async Task readingDataFromConnection(StreamSocket socket)
    {
        Dictionary < string, string> result = new Dictionary<string, string>();
        StringBuilder stringBuilder = new StringBuilder();
        using (Stream inStream = socket.InputStream.AsStreamForRead())
        {
            string line;
            using (StreamReader reader = new StreamReader(inStream))
            {
                do
                {
                    line = await reader.ReadLineAsync();
                    string[] stringSeparators = new string[] { ": " };
                    string[] linesplit;

                    linesplit = line.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);

                    if ((linesplit?.Count() ?? 0) == 2) { result[linesplit[0]] = linesplit[1]; }

                } while (!string.IsNullOrEmpty(line));

                if (result.TryGetValue("Content-Length", out string value))
                {
                    if (Int32.TryParse(value, out int length))
                    {
                        char[] buffer = new char[length];
                        int count = length;

                        count = await reader.ReadBlockAsync(buffer, 0, length);

                        while (count != length)
                        {
                            count += await reader.ReadBlockAsync(buffer, count, length-count);
                        }
                        string data = new string(buffer);
                    }
                }
            }
        }
    }