Reputation: 343
How do I get live (continuous) data from server in C#?
I open HTTPWebRequest but server doesn't complete that request, server sends some text data for every 20 seconds and I want to handle the text data and display to user after 10 minutes server completes the request.
Upvotes: 1
Views: 377
Reputation: 1038930
You could use the streaming API of a WebClient:
var client = new WebClient();
client.OpenReadCompleted += (sender, args) =>
{
using (var reader = new StreamReader(args.Result))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
// do something with the result
// don't forget that this callback
// is not invoked on the main UI thread so make
// sure you marshal any calls to the UI thread if you
// intend to update your UI here.
}
}
};
client.OpenReadAsync(new Uri("http://example.com"));
And here's a full example with the Twitter Streaming API:
using System;
using System.IO;
using System.Net;
class Program
{
static void Main()
{
var client = new WebClient();
client.Credentials = new NetworkCredential("username", "secret");
client.OpenReadCompleted += (sender, args) =>
{
using (var reader = new StreamReader(args.Result))
{
while (!reader.EndOfStream)
{
Console.WriteLine(reader.ReadLine());
}
}
};
client.OpenReadAsync(new Uri("https://stream.twitter.com/1.1/statuses/sample.json"));
Console.ReadLine();
}
}
Upvotes: 2
Reputation: 6265
HTTP is not a session protocol. It was meant to work like this
What you can do is basically Use TCPClient / Socket
instead, which moves you to the layer lower that HTTP and allows you to create persistent connections.
There is variety of frameworks that will make your life easier.
Also, you might want to have a look at Comet.
Upvotes: 2