c++ - native-app 和 chrome-extension 之间的通信

标签 c++ c google-chrome google-chrome-extension chrome-native-messaging

我有一个用 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/

相关文章:

c++ - 我应该返回 std::strings 吗?

c++ - 意外警告 : inline function used but never defined

使用 -h 选项时 javac "no source files"

c - 二叉搜索树的非递归迭代器

c - MPI_CART_CREATE 期间参数

JavaScript Accordion 菜单适用于 IE,不适用于 Chrome 或 Firefox

javascript - Chrome 扩展程序 - 从扩展程序访问文档/页面变量

c++ - 如何使用结构将 "tag"数组编号与字符串一起使用?

c++ - 存储指向同一模板类的模板类型的指针

css - Chrome tr 高度跳过像素