我从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-Events的方法。它有效,我收到通知:
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;
}
}
}
现在我并不总能取得好成绩:
最后一行(xml.Parsed Data)的结果很好:
String: NOTIFY / HTTP/1.1
Host: 192.168.0.20:22111
NT: upnp:event
NTS: upnp:propchange
SID: uuid:57297a21-685b-464c-8c62-d312647472a4
SEQ: 0
Content-Type: text/xml; charset="utf-8"
Connection: close
Accept-Encoding: gzip, deflate
Content-Length: 562
<?xml version="1.0"?><e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0"><e:property><LastChange><Event xmlns="urn:schemas-upnp-org:metadata-1-0/RCS/"><InstanceID val="0"><RoomVolumes val="uuid:29e07ad9-224f-4160-a2bc-61d17845182a=100"/><Volume channel="Master" val="100"/><Mute channel="Master" val="0"/><RoomMutes val="uuid:29e07ad9-224f-4160-a2bc-61d17845182a=0"/></InstanceID></Event></LastChange></e:property></e:propertyset>
没有最后一行(xml-Data)的结果不好:数据丢失了,我不知道为什么?!
String: NOTIFY / HTTP/1.1
Host: 192.168.0.20:22111
NT: upnp:event
NTS: upnp:propchange
SID: uuid:bb3bb2f9-e143-415c-b419-66a72f04d2ff
SEQ: 0
Content-Type: text/xml; charset="utf-8"
Connection: close
Accept-Encoding: gzip, deflate
Content-Length: 215
我也尝试过这个。但它再一次都没有好转。结果是comin,或者我等了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);
}
}
}
}
}
也许这有助于其他人......