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?