c++ - 如何在 PNaCl 中等待 WebSocket 响应

标签 c++ google-chrome websocket google-nativeclient ppapi

我正在通过 PPAPI 中的 pp::WebSocketAPI 在 PNaCl 插件上实现“在继续之前等待 WebSocket 响应”机制。下面是一个简化版本,将回复的数据存储到一个全局的std::string中,而函数myecho()通过WebSocket发送一个字符串,轮询直到全局字符串变化。驱动网页与NaCl SDK中的WebSocket示例相同。

#include <string>
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var.h"
#include "ppapi/cpp/var_array_buffer.h"
#include "ppapi/utility/websocket/websocket_api.h"

class MyWebSocketReceiveListener
{
public:
    virtual void onWebSocketDataReceived(const std::string& data) = 0;
};

class MyWebSocketAPI : protected pp::WebSocketAPI
{
public:
    MyWebSocketAPI(pp::Instance* ppinstance, MyWebSocketReceiveListener* recvlistener)
        : pp::WebSocketAPI(ppinstance), m_onReceiveListener(recvlistener), m_ppinstance(ppinstance) {}
    virtual ~MyWebSocketAPI() {}

    bool isConnected() { return pp::WebSocketAPI::GetReadyState() == PP_WEBSOCKETREADYSTATE_OPEN; }
    void open(const std::string& url) { pp::WebSocketAPI::Connect(url, NULL, 0); }
    void close() { pp::WebSocketAPI::Close(PP_WEBSOCKETSTATUSCODE_NORMAL_CLOSURE, "bye"); }
    void sendData(const std::string& data) { pp::WebSocketAPI::Send(data); }

protected:
    virtual void WebSocketDidOpen() { m_ppinstance->PostMessage("Connected"); }
    virtual void WebSocketDidClose(bool wasClean, uint16_t code, const pp::Var& reason) {}
    virtual void HandleWebSocketMessage(const pp::Var& message)
    {
        if (message.is_array_buffer()) {
            pp::VarArrayBuffer vararybuf(message);
            char *data = static_cast<char*>(vararybuf.Map());
            std::string datastr(data, data + vararybuf.ByteLength());
            vararybuf.Unmap();
            m_onReceiveListener->onWebSocketDataReceived(datastr);
        } else { // is string
            m_onReceiveListener->onWebSocketDataReceived(message.AsString());
        }
    }
    virtual void HandleWebSocketError() {}
private:
    MyWebSocketAPI(const MyWebSocketAPI&);
    MyWebSocketAPI& operator=(const MyWebSocketAPI&);

    MyWebSocketReceiveListener* const m_onReceiveListener;
    pp::Instance * const m_ppinstance;
};

static std::string g_returnval;

class MyPPPluginInstance : public pp::Instance, public MyWebSocketReceiveListener {
public:
    explicit MyPPPluginInstance(PP_Instance instance)
        : pp::Instance(instance), rpcwebsocket_(this, this) {}
    virtual ~MyPPPluginInstance() {}
    virtual void HandleMessage(const pp::Var& var_message);
    virtual void onWebSocketDataReceived(const std::string& data)
    {
        g_returnval = data;
    }

private:
    bool IsConnected() { return rpcwebsocket_.isConnected(); }
    void Open(const std::string& url)
    {
        rpcwebsocket_.open(url);
        PostMessage(pp::Var("connecting..."));
    }
    void Close()
    {
        if (!IsConnected())
            return;
        rpcwebsocket_.close();
    }

    MyWebSocketAPI rpcwebsocket_;
};

std::string myecho(pp::Instance* inst, MyWebSocketAPI& ws, const std::string& in)
{
    ws.sendData(in);
    while (g_returnval.empty()) {
        usleep(1000 * 1000); // 1 sec
        inst->PostMessage("Waiting for response...");
    }
    return g_returnval;
}

void MyPPPluginInstance::HandleMessage(const pp::Var& var_message) {
    if (!var_message.is_string())
        return;
    std::string message = var_message.AsString();
    // This message must contain a command character followed by ';' and
    // arguments like "X;arguments".
    if (message.length() < 2 || message[1] != ';')
        return;
    switch (message[0]) {
    case 'o':
        // The command 'o' requests to open the specified URL.
        // URL is passed as an argument like "o;URL".
        Open(message.substr(2));
        break;
    case 'c':
        // The command 'c' requests to close without any argument like "c;"
        Close();
        break;
    case 'b':
    case 't':
        PostMessage(std::string("Calling remote echo for ") + message.substr(2));
        std::string ret(myecho(this, rpcwebsocket_, message.substr(2)));
        PostMessage(ret);
        break;
    }
}

// Creates MyPPPluginInstance objects when invoked.
class MyPPPluginModule : public pp::Module {
public:
    MyPPPluginModule() : pp::Module() {}
    virtual ~MyPPPluginModule() {}

    virtual pp::Instance* CreateInstance(PP_Instance instance) {
        return new MyPPPluginInstance(instance);
    }
};

// Implement the required pp::CreateModule function that creates our specific
// kind of Module.
namespace pp {
    Module* CreateModule() { return new MyPPPluginModule(); }
}  // namespace pp

然而,这种方法并没有奏效。连接到回显测试服务器 ws://echo.websocket.org 并发送“hello”后,我就得到了

connecting...
Connected
Calling remote echo for hello
Waiting for response...
Waiting for response...
Waiting for response...
Waiting for response...
Waiting for response...

(从不回复)

我使用另一个手工制作的WebSocket服务器进行测试,消息成功发送到服务器。除了我所附代码段中的 usleep() 轮询之外,我还尝试使用 pthread_cond_wait()pthread_cond_signal()等待并通知收到的消息。

如何正确“等待 pp::WebSocketAPI 接收数据”?

最佳答案

myecho() 函数会阻止 MyPPPluginInstance::HandleMessage() 并以某种方式反过来阻止从 WebSocket 接收数据。

我添加了一个 pp::SimpleThread 作为类 MyPPPluginInstance 的新数据成员,并通过 myecho() 分派(dispatch)到另一个线程>pp::SimpleThread::message_loop().PostWork()。它工作顺利。

关于c++ - 如何在 PNaCl 中等待 WebSocket 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30553426/

相关文章:

c++ - 从一维数组中删除多次出现

c++ - 单个 cpp 文件的 Visual Studio 编译选项显示为灰色

C++ 隐式返回返回类型变量

html - 列表样式在不同的浏览器中呈现不同的外观

php - Javascript 连接到 websocket

html - HTML5 是否支持点对点(而不仅仅是 WebSockets)

.net - 如何使命名管道在 C++ 和 .NET 之间工作?

javascript - Chrome : How to abort a script that is stopped at `debugger` statement?

google-chrome - 是否有我可以在本地设置或使用的浏览器选项卡标识符?

python - Cloudscraper 返回 AttributeError : 'SSLContext' object has no attribute 'orig_wrap_socket'