2

我正在尝试使用本机消息将一些数据发送到我的本机 Windows 应用程序。它适用于 runtime.sendNativeMessage() 方法。当我尝试使用使用端口的长期连接时,它还可以将数据从 chrome 传递到我的应用程序。但是,chrome 扩展只能接收来自我的应用程序的第一个响应。我确信端口仍然打开,因为我的应用程序仍然可以从 chrome 接收数据。以下是我的代码:

Chrome 扩展脚本:

var port = chrome.runtime.connectNative('com.mydomain.app1');

port.onMessage.addListener(function(msg) {
    console.log("Received from port:", msg);
});

port.onDisconnect.addListener(function() {
    console.log("Disconnected");
});

chrome.tabs.onUpdated.addListener(
    function(tabId, changeInfo, tab) {  
        var param = {};
        param['url'] = tab.url; 
        port.postMessage( param);   
    }
}

我在 C++ 中的 Windows 应用程序:

int _tmain(int argc, _TCHAR* argv[])
{
    while( true )
    {
         //read the first four bytes (=> Length)
         unsigned int length = 0;
         for (int i = 0; i < 4; i++)
         {
              char c;
              if( ( c=getchar()) != EOF) 
                  length += c<<i*8;
              else return 0;
          }

          //read the json-message
          std::string msg = "";
          for (int i = 0; i < length; i++)
          {
              msg += getchar();
          } 

          //.... do something

          //send a response message
          std::string message = "{\"text\": \"This is a response 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.c_str();
           std::cout.flush();
          
     }
}   

请注意最后一行“ std::cout.flush(); ”,如果我将其注释掉,即使是第一个响应也不会在 chrome 中显示。我只是无法弄清楚 chrome 如何从应用程序的标准输出中读取。

4

1 回答 1

2

尝试自动冲洗 -std::cout.setf( std::ios_base::unitbuf )

此外,您读/写输入/输出消息长度的方式不正确,并且会在长消息上失败。

这段代码对我很有效:

int main(int argc, char* argv[])
{
    std::cout.setf( std::ios_base::unitbuf );

    while (true)
    {
        unsigned int ch, inMsgLen = 0, outMsgLen = 0;
        std::string input = "", response = "";

        // Read 4 bytes for data length
        std::cin.read((char*)&inMsgLen, 4);

        if (inMsgLen == 0)
        {
            break;
        }
        else
        {
            // Loop getchar to pull in the message until we reach the total length provided.
            for (int i=0; i < inMsgLen; i++)
            {
                ch = getchar();
                input += ch;
            }
        }

        response.append("{\"echo\":").append(input).append("}");

        outMsgLen = response.length();

        // Send 4 bytes of data length
        std::cout.write((char*)&outMsgLen, 4);

        // Send the data
        std::cout << response;
    }

    return 0;
}
于 2014-05-27T11:28:05.330 回答