简体   繁体   中英

Keep-Alive connection for notifications C#

I need to show a notification on the user's dekstop whenever the text taken from a website (that requires POST method to login) changes. The website has a table with text that can be edited by the admin, so the string containing the HTML page source changes. I think that the connection should be always active in order to provide real-time notification. I already have the code to perform the login to the website, but the connection closes when the method ends.

My problem is: what's the best way to archive keep-alive connection and show a notification on the desktop?

Here's the login code:

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;
    }

The best approach is to use SignalR, not HTTP. If you don't control the server and SignalR isn't available, then you'll need to just poll on some interval.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM