我正在尝试使用本机消息传递将一些数据发送到我的本机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();
}
}
请注意最后一行&#34; std :: cout.flush(); &#34;,如果我将其评论出来,即使是第一个回复也不会被显示在铬。我只是无法弄清楚Chrome如何从应用程序的标准中读取。
答案 0 :(得分: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;
}