0
我們有這個URL 連接不會關閉,並繼續無限期地每隔幾秒發送一次響應。如何使用c#從連續響應的網頁中獲取數據(部分)?
我想獲取部分數據,但使用當前代碼,它會在顯示數據之前等待連接結束或關閉,但由於此網頁無限響應,我編寫的程序也無限期地等待。
但與其他測試網址,如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;
}
}
如果你有進一步的說明,請不要問。
答案更新 由於勒,我所做的就是這樣的。
下面是完整的回答我的問題:
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;
}
}
非常感謝,這幫助我解決了我的問題。 – jestrange