I have a native-app written in c++.
I am able to send data from my native-app to chrome extension using How to send message FROM native app TO Chrome extension?
But I am unable to figure out the other way.
Chrome doc. states : Chrome starts each native messaging host in a separate process and communicates with it using standard input (stdin) and standard output (stdout). The same format is used to send messages in both directions: each message is serialized using JSON, UTF-8 encoded and is preceded with 32-bit message length in native byte order.
how do I read/interpret data from stdin, sent by the chrome-extension?
How do I read 4byte length information and also the rest of the data that is being sent UTF-8 encoded?
Please help!
Thanks!
To read the json-data from stdin:
int _tmain(int argc, _TCHAR* argv[])
{
unsigned int length = 0;
//read the first four bytes (=> Length)
for (int i = 0; i < 4; i++)
{
length += getchar();
}
//read the json-message
string msg = "";
for (int i = 0; i < length; i++)
{
msg += getchar();
}
}
As someone mentioned in the comments, the provided solution won't work if the length is greater than 255. For example, if actual length is 296 (binary 00000001 00101000) the solution presented earlier will produce 41 => 00000001 + 00101000 = 1 + 40 = 41.
The number of byte that is read must be taken into consideration. In this example, the correct way to calculate the length is 1*(2^8) + 40 = 296. So the correct solution might be:
unsigned int length = 0;
//read the first four bytes
for (int i = 0; i < 4; i++) {
int read_char = getchar();
length += read_char * (int) pow(2.0, i * 8);
}
Better solution based on shifting of bits and bit operations is presented below (perhaps little bit harder to understand but for sure neater):
unsigned int length = 0;
for (int i = 0; i < 4; i++) {
unsigned int read_char = getchar();
length = length | (read_char << i * 8);
}
It is important to notice that getchar() returns int that is cast to unsigned int before performing bit OR with current value of length (int has one bit reserved for sign, unsigned int doesn't).
Now, I am not sure about potential big/little endian problems that may appear here as I haven't tested this solution on different architectures. I hope someone with more experience can comment on this.
来源:https://stackoverflow.com/questions/20211166/how-to-send-message-from-chrome-extension-to-native-app