communication between native-app and chrome-extension

前端 未结 3 1145
栀梦
栀梦 2020-12-05 21:53

I have a native app written in c++ and a chrome-extension.

I am communicating between them using \'chrome native messaging\'.

Native-App code:



        
相关标签:
3条回答
  • 2020-12-05 21:58

    This works for me:

     int main(int argc, char* argv[])
     {
    
     std::cout.setf( std::ios_base::unitbuf ); //instead of "<< eof" and "flushall"
     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;
    }
    

    ...

    0 讨论(0)
  • 2020-12-05 22:05

    The string length decode algorithm is incorrect. This is the correction:

    for (i = 0; i <= 3; i++) {
        c = getchar();
        l |= (c << 8*i);
    }
    
    0 讨论(0)
  • 2020-12-05 22:18

    Marc's answer contains some errors (inherited from the question) and will not work for messages with lengths that do not fit in one byte.

    Chrome's protocol, when communicating with native apps is:

    • requests to native app are received through stdin
    • responses to Chrome are sent through stdout
    • Chrome doesn't deal well with Windows style \r\n so avoid that in the messages and set stdin mode to binary (so you can correctly read the request len and \n doesn't 'turn' into \r\n):

      _setmode(_fileno(stdin),_O_BINARY);
      

    The request and response messages are JSON with a 4 byte header (uint32) containing the length of the message: [length 4 byte header][message]

    Reading the request header:

    uint32_t reqLen = 0;
    cin.read(reinterpret_cast<char*>(&reqLen) ,4);
    

    Writing the response header:

    cout.write(reinterpret_cast<char*>(&responseLen),4); 
    
    0 讨论(0)
提交回复
热议问题