通知的保持活动连接C#
本文关键字:连接 活动 通知 | 更新日期: 2023-09-27 17:58:02
每当从网站获取的文本(需要POST方法登录)发生更改时,我都需要在用户的dekstop上显示通知。该网站有一个包含可由管理员编辑的文本的表,因此包含HTML页面源的字符串会发生更改。我认为连接应该始终处于活动状态,以便提供实时通知。我已经有了登录网站的代码,但当方法结束时,连接就会关闭。
我的问题是:归档保持连接并在桌面上显示通知的最佳方式是什么?
这是登录代码:
public async static Task<string> LoginAsync(string reqUri, string postData)
{
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(reqUri);
// Set the Method property of the request to POST.
request.Method = "POST";
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Convert POST data to a byte array.
byte[] data = Encoding.UTF8.GetBytes(postData);
// Get request stream and write data to it
using (var requestStream = await Task<Stream>.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, null))
{
await requestStream.WriteAsync(data, 0, data.Length);
}
return await GetResponse(request);
}
private async static Task<string> GetResponse(HttpWebRequest request)
{
string _response = null;
// Get response from the website
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
// Get the response stream
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(responseStream, Encoding.GetEncoding("iso-8859-1")))
{
// Get the response string from the website
_response = await sr.ReadToEndAsync();
}
}
}
return _response;
}
最好的方法是使用SignalR,而不是HTTP。如果你无法控制服务器,SignalR不可用,那么你只需要每隔一段时间进行轮询。