2

I'm writing a Chrome extension that uses native messaging and it all works fine. The issue I'm addressing in on the native application side.

The Chrome extension communicates with the native application using stdin and stdout and I'm having trouble finding a good way of listening for input.

Right now my code looks like this:

using (Stream stdin = Console.OpenStandardInput(),
          stdout = Console.OpenStandardOutput())
{

    while (true)
    {
        var input = ReadInputFromStream(stdin);

        if (input == string.Empty)
        {
            System.Threading.Thread.Sleep(50);

            continue;
        }

        // Do some work and send response
    }
}

And the ReadInputStream method:

private static string ReadInputFromStream(Stream stream)
{
    var buff = new byte[4];

    stream.Read(buff, 0, 4);

    var len = BitConverter.ToInt32(buff, 0);

    buff = new byte[len];
    stream.Read(buff, 0, len);

    return Encoding.UTF8.GetString(buff);
}

I'd really like to avoid the sleep and instead have the application blocked until input is received. Stream.Read returns zero as no data is found, so it keeps looping.

Is there a nice solution to this issue?

Loofer
  • 6,841
  • 9
  • 61
  • 102
Casper
  • 179
  • 1
  • 1
  • 11
  • What .NET version are you using? – Dennis Oct 20 '15 at 08:44
  • "The implementation will block until at least one byte of data can be read", from https://msdn.microsoft.com/en-us/library/system.io.stream.read%28v=vs.100%29.aspx. Meaning, he sleep is unnecessary. – Peter - Reinstate Monica Oct 20 '15 at 09:04
  • Oh, I read only now that you receive a 0. That is an end-of-file indicator. Your input has run empty. Time to close the program. (But in all reality, I do not see your code check the return value of `Read()`. How do you know it returned 0? – Peter - Reinstate Monica Oct 20 '15 at 09:07
  • Thank you for your comment. I do not want to close the program. It needs to keep running. The return value from `Read` is put into the variable `buff`, which is returned and used in the first part of the code (in the while loop). – Casper Oct 20 '15 at 10:05

0 Answers0