BadVolt
BadVolt

Reputation: 637

Read endless stream with HttpWebRequest C#

I'm using C# to get data from endless http-stream. I used TCP Client before, but now I want to add status code exceptions, it's much easier to do it with HttpWebResponse. I got response, but problem is I can't read chunks coming from server. Everything looks fine, but I must be missed something. Debug shows execution is stucked at ReadLine(). Also I can see there's some data in stream buffer.

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://" + url + "/stream/" + from + "?token=" + token);
using(HttpWebResponse res = (HttpWebResponse)req.GetResponse())
using(StreamReader streadReader = new StreamReader(res.GetResponseStream(),Encoding.UTF8)){
    //Start parsing cycle
    while(!streadReader.EndOfStream && !worker.CancellationPending) {
        string resultLine = streadReader.ReadLine();
        System.Diagnostics.Trace.WriteLine(resultLine);
        if(!resultLine.StartsWith("{")) continue;
        newQuote quote = JsonConvert.DeserializeObject<newQuote>(resultLine);
        worker.ReportProgress(0, quote);
    }
}

Upvotes: 1

Views: 1323

Answers (1)

BadVolt
BadVolt

Reputation: 637

I'v found the error. I was using ReadLine(), but never sent "\r\n" from server side. I patched my server to send \r\n after JSON object ant it works fine now. Another option is to use Read() method. It's not waiting for the end of line, but you must know chunk length. Thanks for the help :)

Upd: How to parse string using Read() method:

    while(!streamReader.EndOfStream && !worker.CancellationPending) {
    char[] buffer = new char[1024];
    streamReader.Read(buffer, 0, buffer.Length);
    string resultLine="";
    for(int i = 0; i < buffer.Length; i++) {
        if(buffer[i] != 0) resultLine += buffer[i].ToString();
    }
    newQuote quote = JsonConvert.DeserializeObject<newQuote>(resultLine);
    worker.ReportProgress(0, quote);
}

Upvotes: 1

Related Questions