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

roh*_*tvk 7 c c++ google-chrome google-chrome-extension chrome-native-messaging

我有一个用c ++和chrome扩展编写的本机应用程序.

我正在使用"chrome native messaging"在它们之间进行通信.

Native-App代码:

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;  }
Run Code Online (Sandbox Code Playgroud)

在这里,我正在读取由stdin上的chrome-extension发送的消息.并通过在stdout上写回来发送相同的消息.

扩展使用PostMessage()

这工作......但是......

当我将程序置于连续的while循环中时,流程只执行一次!

即port.postMessage({'text':'hello_1'})按预期回复,但如果我这样做

port.postMessage({'text':'hello_2'})它没有得到回应.

我无法理解问题所在.它需要线程吗?

请帮忙!

谢谢!

小智 10

Marc的答案包含一些错误(继承自问题),并且不适用于长度不适合一个字节的消息.

Chrome与本机应用进行通信时的协议是:

  • 对本机应用程序的请求是通过stdin接收的
  • 对Chrome的回复是通过stdout发送的
  • Chrome无法很好地处理Windows样式\ r \n,因此请避免在消息中将stdin模式设置为二进制(因此您可以正确读取请求len并且\n不会'转'到\ r \n):

    _setmode(_fileno(stdin),_O_BINARY);
    
    Run Code Online (Sandbox Code Playgroud)

请求和响应消息是带有4字节头(uint32)的JSON,其中包含消息的长度:[长度为4字节的头部] [消息]

阅读请求标题:

uint32_t reqLen = 0;
cin.read(reinterpret_cast<char*>(&reqLen) ,4);
Run Code Online (Sandbox Code Playgroud)

编写响应头:

cout.write(reinterpret_cast<char*>(&responseLen),4); 
Run Code Online (Sandbox Code Playgroud)