从本地主机向浏览器插件发送消息时出现“与本地消息主机通信时出错。”的错误提示(Windows)

3
我收到一个“Inside onDisconnected(): Error when communicating with the native messaging host.”错误,当我从本机主程序向浏览器扩展发送消息时。
有几个可能引起这个问题:
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);
}

所有可能的三个原因似乎都不是发生的原因。但是我无法找到任何详细信息(即使从谷歌提供的源代码中查看),了解导致我的特定错误消息的原因。WriteFile()成功执行,写入的字节数为22个字节。总共写入了22个字节,其中4个字节是长度字节。我已经验证前4个字节为(以十进制表示,而非十六进制):18,0,0,0,这在小端格式下表示构成json消息的后续字节数。当我使用DebugView窥视我的json消息时,它总是:{"results":"0000"}。这是18个字节/字符。我甚至尝试发送转义的双引号,以防这是首选方法。在浏览器扩展的后台页面上,我的onDisconnected()事件被调用,报告最后一个chrome运行时错误消息(这就是我得到定义此问题的错误消息的地方)。这意味着扩展和本机主机应用程序之间的连接正在关闭。非常感谢您的帮助。

你应该从bufMsg中写入,而不是pMessageBytes。现在你只是写入了字符串,而没有写入长度。此外,在写入后可能需要使用FlushFileBuffers。 - donaddon
啊,确实是这个问题。谢谢。请将您的解决方案作为答案回复,以便我将其标记为正确。 - Alyoshak
1个回答

2

您应该使用bufMsg与WriteFile一起使用。您正在使用pMessageBytes,这只是发送字符串而不是长度前缀。

您还应该考虑在WriteFile调用后使用FlushFileBuffers,因为通常情况下,您希望本机应用程序通信立即发送。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接