0

I have a chrome native messaging host application that reads JSON messages from STDIN and writes data to STDOUT.

The problem I am facing right now is with the StreamReader.Peek() method.

On debugging on first iteration it runs successfully, but on second iteration it breaks at reader.Peek() point with out throwing any exception.

The control just goes away without any exception.

var length = 0;
var lengthBytes = new byte[4];
stdin.Read(lengthBytes, 0, 4);
length = BitConverter.ToInt32(lengthBytes, 0);

var messageBuffer = new char[length];
using (var reader = new StreamReader(stdin))
{
    while (reader.Peek() >= 0)
    {
        reader.Read(messageBuffer, 0, messageBuffer.Length);
    }
}

var message = new string(messageBuffer);
Log.Debug(message);
var jsonMessageObject = JsonConvert.DeserializeObject<JObject>(message);

if (jsonMessageObject == null)
{
    return null;
}

Can someone help how to know whats going wrong even though it had read all the data perfectly?

Why is Peek() breaking without any exception?

absoluteAquarian
  • 510
  • 3
  • 12
Maninder
  • 1,261
  • 5
  • 20
  • 34
  • Is there any reason at all for calling `Peek`, as opposed to just letting `Read` return what you need? – Jeroen Mostert Oct 18 '18 at 13:37
  • I have followed https://stackoverflow.com/questions/30880709/c-sharp-native-host-with-chrome-native-messaging link to create a host that will read messages written to STDIN and do the processing. – Maninder Oct 18 '18 at 13:46
  • Anyway, please double confirm that your "stdin" has the length that greater than (messageBuffer.Length+4), or otherwise it is normal because all data has gone into the buffer and the source stream is essentially now EOF, which will give you -1 and kick you out from the while-loop. Normally as being said, you seldom use Peek() because most of the time you will be dealing with higher level reading calls. – LoL Oct 18 '18 at 13:48
  • Yes I am expecting -1 but the evaluation of reader.Peek() statement returns nothing and breaks or exits silently without any exception. – Maninder Oct 18 '18 at 13:52
  • @JeroenMostert on removing the Peek call solves my issues. But just wanted to confirm from you if this won't be of any negative impact and just using Read() will work for my app. – Maninder Oct 18 '18 at 14:03
  • You have to properly process the return value of `Read` to detect the end of the stream, but other than that there should be no issue. The way `Peek` is used here is not meaningful; it would be meaningful if anything *other* than reading the stream was done as a result of the peek. – Jeroen Mostert Oct 18 '18 at 14:19
  • Thanks a lot @JeroenMostert – Maninder Oct 19 '18 at 09:40

0 Answers0