为了让原生消息传递主机将数据发送回 Chrome,您必须先发送四个字节的长度信息,然后将 JSON 格式的消息作为字符串/字符数组发送。
以下分别是 C 和 C++ 的两个示例,它们以略微不同的方式执行相同的操作。
C 示例:
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[]) {
// Define our message
char message[] = "{\"text\": \"This is a response message\"}";
// Collect the length of the message
unsigned int len = strlen(message);
// We need to send the 4 bytes of length information
printf("%c%c%c%c", (char) (len & 0xff),
(char) ((len>>8) & 0xFF),
(char) ((len>>16) & 0xFF),
(char) ((len>>24) & 0xFF));
// Now we can output our message
printf("%s", message);
return 0;
}
C++ 示例:
#include <string.h>
int main(int argc, char* argv[]) {
// Define our message
std::string message = "{\"text\": \"This is a response message\"}";
// Collect the length of the message
unsigned int len = message.length();
// We need to send the 4 bytes of length information
std::cout << char(((len>>0) & 0xFF))
<< char(((len>>8) & 0xFF))
<< char(((len>>16) & 0xFF))
<< char(((len>>24) & 0xFF));
// Now we can output our message
std::cout << message;
return 0;
}
(实际消息可以与长度信息同时发送;只是为了清楚起见将其分开。)
所以按照 OP Chrome 的例子,这里是如何输出消息的:
port.onMessage.addListener(function(msg) {
console.log("Received" + msg.text);
});
实际上,不需要使用“文本”作为从您的本地消息传递应用程序返回的键;它可以是任何东西。从您的本机消息传递应用程序传递给侦听器的 JSON 字符串将转换为 JavaScript 对象。
有关将上述技术与 jsoncpp(C++ JSON 库)结合使用并解析发送到应用程序的请求的原生消息传递应用程序的 C++ 示例,请参见此处:https://github.com/kylehuff/libwebpg/blob/22d4843f41670d4fd7c4cc7ea3cf833edf8f1baf/webpg.cc#L4501