我有一个用 C++ 和一个 chrome 扩展程序编写的 native 应用程序。
我正在使用“chrome 原生消息”在它们之间进行通信。
native 应用程序代码:
int main(int argc, char* argv[]) {
unsigned int a, c, i, t=0;
std::string inp; do {
inp="";
t=0;
// Sum the first 4 chars from stdin (the length of the message passed).
for (i = 0; i <= 3; i++) {
t += getchar();
}
// Loop getchar to pull in the message until we reach the total
// length provided.
for (i=0; i < t; i++) {
c = getchar();
inp += c;
}
// Collect the length of the message
unsigned int len = inp.length();
//// We need to send the 4 btyes 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 << inp <<std::endl;
flushall();
}while(cnt < 2 );
return 0; }
在这里,我正在阅读由 stdin 上的 chrome-extension 发送的消息。并通过将其写入标准输出来发回相同的消息。
扩展正在使用 PostMessage()
这是有效的...但是...
当我将程序置于连续的 while 循环中时,流程只执行一次!
即 port.postMessage({'text':'hello_1'}) 按预期得到回显,但如果我这样做了
port.postMessage({'text':'hello_2'}) 它没有得到回应。
我无法理解问题所在。是否需要线程?
请帮忙!
谢谢!
最佳答案
Marc 的回答包含一些错误(继承自问题)并且不适用于长度不适合一个字节的消息。
Chrome 的协议(protocol),在与 native 应用程序通信时是:
- 通过标准输入接收对 native 应用程序的请求
- 对 Chrome 的响应通过标准输出发送
Chrome 不能很好地处理 Windows 风格\r\n 因此请避免在消息中出现这种情况并将标准输入模式设置为二进制(以便您可以正确读取请求 len 并且\n 不会“转”为\r\n):
_setmode(_fileno(stdin),_O_BINARY);
请求和响应消息是 JSON,带有包含消息长度的 4 字节 header (uint32): [长度为 4 字节的 header ][消息]
读取请求头:
uint32_t reqLen = 0;
cin.read(reinterpret_cast<char*>(&reqLen) ,4);
编写响应头:
cout.write(reinterpret_cast<char*>(&responseLen),4);
关于c++ - native-app 和 chrome-extension 之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20220668/