如何使用c#从连续响应的网页中获取数据(部分)?

时间:2017-02-06 09:35:03

标签: c# asynchronous web webclient

我们有URL 连接不会关闭,并且每隔一秒左右就会无限期地继续发送响应。

我想获取部分数据但是使用我当前的代码,它会在显示数据之前等待连接结束或关闭,但由于此网页无限期响应,我写的程序也会无限期地等待。

但是使用其他测试网址(例如www.google.com)会立即关闭连接,它可以正常工作。

这是我的代码:

public partial class Form2 : Form
{
    string testurl = "https://live.wh.sportingpulseinternational.com/v1/basketball/read/448426?ak=6eea426648c256cae71a9409352304fe&types=scoreboard,status,boxscore&format=json";

    WebClient wc = new WebClient();
    public Form2()
    {
        InitializeComponent();

        wc.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadComplete);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        wc.DownloadDataAsync(new Uri(testurl));
        button1.Enabled = false;
    }

    private void DownloadComplete(object sender, DownloadDataCompletedEventArgs args)
    {
        byte[] result = args.Result;
        richTextBox1.Text += System.Text.Encoding.Default.GetString(result);
        button1.Enabled = true;
    }
}

如果您有进一步的说明,请询问。

答案更新 感谢 levent ,我所做的就是这样。

以下是我的问题的完整答案:

    string testurl = "https://live.wh.sportingpulseinternational.com/v1/basketball/read/448426?ak=6eea426648c256cae71a9409352304fe&types=scoreboard,status,boxscore&format=json";
    BackgroundWorker worker = new BackgroundWorker();

    public Form2()
    {
        InitializeComponent();

        worker.WorkerSupportsCancellation = true;
        worker.DoWork += new DoWorkEventHandler(worker_DoWork);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        SetEnabled(button1, false);
        worker.RunWorkerAsync();
    }

    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        string url = testurl;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        using (WebResponse response = request.GetResponse())
        {
            using (StreamReader rdr = new StreamReader(response.GetResponseStream()))
            {
                try
                {
                    while (!rdr.EndOfStream)
                    {
                        var str = rdr.ReadLine();
                        SetText(richTextBox1, str);
                    }
                }
                catch (Exception)
                {

                }
            }
        }
        worker.CancelAsync();
        SetEnabled(button1, true);
    }

    delegate void SetEnabledCallback(Button target, bool value);
    private void SetEnabled(Button target, bool value)
    {
        if (target.InvokeRequired)
        {
            SetEnabledCallback d = new SetEnabledCallback(SetEnabled);
            this.Invoke(d, new object[] { target, value });
        }
        else
        {
            target.Enabled = value;
        }
    }

    delegate void SetTextCallback(dynamic target, string text);
    private void SetText(dynamic target, string text)
    {
        if (target.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke(d, new object[] { target, text });
        }
        else
        {
            target.Text += text;
        }
    }

1 个答案:

答案 0 :(得分:1)

此代码读取消息,您可以在asycn操作中运行它。

         string url = "https://live.wh.sportingpulseinternational.com/v1/basketball/read/448426?ak=6eea426648c256cae71a9409352304fe&types=scoreboard,status,boxscore&format=json%22link%22";
         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
         using(WebResponse response =  request.GetResponse())
         {
             using(StreamReader rdr = new StreamReader(response.GetResponseStream())){
                 while(!rdr.EndOfStream){
                     var str = rdr.ReadLine();
                     Console.WriteLine(str);
                 }
             }
         }