我收到“Inside onDisconnected(): Error when communication with the native messaging host”。从我的 native 主机应用程序向浏览器扩展程序发送消息时。
有几种情况会导致这种情况:
1) 消息开头发送的长度不正确,或发送的长度字节顺序不正确(字节顺序)。
2) 在写入之前不要将 stdout 置于二进制模式(如果 stdout 处于文本模式,可以在代码之外添加额外的字节)。
3) 不以 UTF-8 格式将消息作为有效的 json 发送。实际上我不确定无效的 json 会被拒绝,但文档说消息应该是 json。
代码是:
int nStdOutDescriptor = _fileno(stdout);
int result = _setmode( nStdOutDescriptor, _O_BINARY );
if( result == -1 )
{
OutputDebugStringA ("Failed attempting to set stdout to binary mode\r\n");
return;
}
HANDLE hStdOut = (HANDLE) _get_osfhandle(nStdOutDescriptor);
if (INVALID_HANDLE_VALUE != hStdOut)
{
char *results = "{\"results\":\"0000\"}";
std::string sMsg(results);
int nMsgLen = sMsg.length();
unsigned char first = (unsigned char)(nMsgLen & 0x000000ff);
unsigned char second = (unsigned char)((nMsgLen >> 8) & 0x000000ff);
unsigned char third = (unsigned char)((nMsgLen >> 16) & 0x000000ff);
unsigned char fourth = (unsigned char)((nMsgLen >> 24) & 0x000000ff);
char *bufMsg = new char[4 + nMsgLen]; // allocate message buffer
const char *pMessageBytes = sMsg.c_str();
memcpy( &bufMsg[4], &pMessageBytes[0], nMsgLen);
bufMsg[0] = first;
bufMsg[1] = second;
bufMsg[2] = third;
bufMsg[3] = fourth;
DWORD dwNumBytesToWrite = nMsgLen + 4;
DWORD dwNumBytesWritten;
if (TRUE == WriteFile(hStdOut, (LPVOID)pMessageBytes, dwNumBytesToWrite, &dwNumBytesWritten, NULL))
{
BTrace (L"WriteFile() succeeded. Returned TRUE. %lu bytes written", dwNumBytesWritten );
}
_close(nStdOutDescriptor);
}
这三种可能的原因似乎都没有发生。但是我找不到任何关于导致我的特定错误消息的详细信息(即使是查看 Google 提供的来源)。 WriteFile()成功,写入的字节数为22字节。总共写入了 22 个字节,其中 4 个是长度字节。我已经验证前 4 个字节是(十进制,而不是十六进制):18,0,0,0,它以小端方式表示构成 json 消息的字节数。当我使用 DebugView 查看我的 json 消息时,它总是:{"results":"0000"}。那是 18 个字节/字符。我什至尝试过发送转义双引号以防万一。在浏览器扩展的后台页面中,我的 onDisconnected() 事件被调用,它报告了最后一条 chrome 运行时错误消息(这是我收到定义此问题的错误消息的地方)。这意味着扩展程序和 native 主机应用程序之间的连接正在关闭。将不胜感激。
最佳答案
您应该将 bufMsg 与 WriteFile 一起使用。您正在使用 pMessageBytes,它只是发送字符串而不是长度前缀。
您还应该考虑在 WriteFile 调用之后使用 FlushFileBuffers,因为作为一般规则,您会希望立即发送 native 应用程序通信。
关于google-chrome - 从 native 主机向浏览器扩展发送消息时获取 "Error when communicating with the native messaging host."(Windows),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28439776/