1

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);
    }
}
4
  • 1
    So is there maybe a very long line or no line break at all? Code looks fine. Commented Sep 10, 2015 at 15:21
  • 1
    This kind of error handling is really worrying: if(!resultLine.StartsWith("{")) continue;. Delete that. Commented Sep 10, 2015 at 15:22
  • @usr Or create a better magic to determine the end of the chunk. Commented Sep 10, 2015 at 15:23
  • Yeah, it's kinda hacky, must admit that. It left from TCP client, Not every chunk was an object there :) I will remove it, thank you. @usr, you was right. I was using ReadLine but never send \r\n from server-side. Commented Sep 10, 2015 at 15:30

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.