通知C#的Keep-Alive连接

时间:2014-04-11 22:03:38

标签: c# windows post notifications keep-alive

每当从网站(需要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;
    }

1 个答案:

答案 0 :(得分:0)

最好的方法是使用SignalR,而不是HTTP。如果您无法控制服务器并且SignalR不可用,那么您只需要在某个时间间隔内进行轮询。