2019-05-17 07:41:39 +02:00
|
|
|
/*
|
|
|
|
* IXWebSocketMessageQueue.cpp
|
|
|
|
* Author: Korchynskyi Dmytro
|
|
|
|
* Copyright (c) 2017-2019 Machine Zone, Inc. All rights reserved.
|
|
|
|
*/
|
|
|
|
|
|
|
|
#include "IXWebSocketMessageQueue.h"
|
|
|
|
|
|
|
|
namespace ix
|
|
|
|
{
|
|
|
|
WebSocketMessageQueue::WebSocketMessageQueue(WebSocket* websocket)
|
|
|
|
{
|
|
|
|
bindWebsocket(websocket);
|
|
|
|
}
|
|
|
|
|
|
|
|
WebSocketMessageQueue::~WebSocketMessageQueue()
|
|
|
|
{
|
|
|
|
if (!_messages.empty())
|
|
|
|
{
|
|
|
|
// not handled all messages
|
|
|
|
}
|
|
|
|
|
|
|
|
bindWebsocket(nullptr);
|
|
|
|
}
|
|
|
|
|
2019-09-23 19:25:23 +02:00
|
|
|
void WebSocketMessageQueue::bindWebsocket(WebSocket* websocket)
|
2019-05-17 07:41:39 +02:00
|
|
|
{
|
|
|
|
if (_websocket == websocket) return;
|
|
|
|
|
|
|
|
// unbind old
|
|
|
|
if (_websocket)
|
|
|
|
{
|
|
|
|
// set dummy callback just to avoid crash
|
2019-06-09 20:33:17 +02:00
|
|
|
_websocket->setOnMessageCallback([](const WebSocketMessagePtr&) {});
|
2019-05-17 07:41:39 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
_websocket = websocket;
|
|
|
|
|
|
|
|
// bind new
|
|
|
|
if (_websocket)
|
|
|
|
{
|
2019-09-23 19:25:23 +02:00
|
|
|
_websocket->setOnMessageCallback([this](const WebSocketMessagePtr& msg) {
|
2019-06-09 20:33:17 +02:00
|
|
|
std::lock_guard<std::mutex> lock(_messagesMutex);
|
|
|
|
_messages.emplace_back(std::move(msg));
|
2019-05-17 07:41:39 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void WebSocketMessageQueue::setOnMessageCallback(const OnMessageCallback& callback)
|
|
|
|
{
|
|
|
|
_onMessageUserCallback = callback;
|
|
|
|
}
|
|
|
|
|
|
|
|
void WebSocketMessageQueue::setOnMessageCallback(OnMessageCallback&& callback)
|
|
|
|
{
|
|
|
|
_onMessageUserCallback = std::move(callback);
|
|
|
|
}
|
2019-06-06 02:04:24 +02:00
|
|
|
|
2019-06-09 19:22:27 +02:00
|
|
|
WebSocketMessagePtr WebSocketMessageQueue::popMessage()
|
2019-05-17 07:41:39 +02:00
|
|
|
{
|
2019-06-09 19:22:27 +02:00
|
|
|
WebSocketMessagePtr message;
|
2019-05-17 07:41:39 +02:00
|
|
|
std::lock_guard<std::mutex> lock(_messagesMutex);
|
|
|
|
|
|
|
|
if (!_messages.empty())
|
|
|
|
{
|
|
|
|
message = std::move(_messages.front());
|
|
|
|
_messages.pop_front();
|
|
|
|
}
|
|
|
|
|
|
|
|
return message;
|
|
|
|
}
|
|
|
|
|
|
|
|
void WebSocketMessageQueue::poll(int count)
|
|
|
|
{
|
2019-09-23 19:25:23 +02:00
|
|
|
if (!_onMessageUserCallback) return;
|
2019-05-17 07:41:39 +02:00
|
|
|
|
2019-06-09 19:22:27 +02:00
|
|
|
WebSocketMessagePtr message;
|
2019-05-17 07:41:39 +02:00
|
|
|
|
|
|
|
while (count > 0 && (message = popMessage()))
|
|
|
|
{
|
2019-06-09 20:33:17 +02:00
|
|
|
_onMessageUserCallback(message);
|
2019-05-17 07:41:39 +02:00
|
|
|
--count;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-23 19:25:23 +02:00
|
|
|
} // namespace ix
|