2018-08-22 07:08:48 +00:00
|
|
|
#include "WebSocketTest.h"
|
|
|
|
using namespace example;
|
2020-11-14 03:48:40 +00:00
|
|
|
struct Subscriber
|
|
|
|
{
|
|
|
|
std::string chatRoomName_;
|
|
|
|
drogon::SubscriberID id_;
|
|
|
|
};
|
2019-05-18 12:39:57 +00:00
|
|
|
void WebSocketTest::handleNewMessage(const WebSocketConnectionPtr &wsConnPtr,
|
|
|
|
std::string &&message,
|
|
|
|
const WebSocketMessageType &type)
|
2018-08-22 07:08:48 +00:00
|
|
|
{
|
2019-05-18 12:39:57 +00:00
|
|
|
// write your application logic here
|
2019-01-17 05:51:25 +00:00
|
|
|
LOG_DEBUG << "new websocket message:" << message;
|
2019-04-06 15:06:38 +00:00
|
|
|
if (type == WebSocketMessageType::Ping)
|
|
|
|
{
|
|
|
|
LOG_DEBUG << "recv a ping";
|
|
|
|
}
|
2020-11-14 03:48:40 +00:00
|
|
|
else if (type == WebSocketMessageType::Text)
|
|
|
|
{
|
|
|
|
auto &s = wsConnPtr->getContextRef<Subscriber>();
|
|
|
|
chatRooms_.publish(s.chatRoomName_, message);
|
|
|
|
}
|
2018-08-23 05:17:54 +00:00
|
|
|
}
|
2019-04-06 15:06:38 +00:00
|
|
|
|
2020-11-14 03:48:40 +00:00
|
|
|
void WebSocketTest::handleConnectionClosed(const WebSocketConnectionPtr &conn)
|
2018-08-27 08:07:36 +00:00
|
|
|
{
|
2019-01-17 05:51:25 +00:00
|
|
|
LOG_DEBUG << "websocket closed!";
|
2020-11-14 03:48:40 +00:00
|
|
|
auto &s = conn->getContextRef<Subscriber>();
|
|
|
|
chatRooms_.unsubscribe(s.chatRoomName_, s.id_);
|
2018-08-27 08:07:36 +00:00
|
|
|
}
|
2019-04-06 15:06:38 +00:00
|
|
|
|
2020-11-14 03:48:40 +00:00
|
|
|
void WebSocketTest::handleNewConnection(const HttpRequestPtr &req,
|
2019-01-17 05:51:25 +00:00
|
|
|
const WebSocketConnectionPtr &conn)
|
2018-08-27 08:07:36 +00:00
|
|
|
{
|
2019-01-17 05:51:25 +00:00
|
|
|
LOG_DEBUG << "new websocket connection!";
|
|
|
|
conn->send("haha!!!");
|
2020-11-14 03:48:40 +00:00
|
|
|
Subscriber s;
|
|
|
|
s.chatRoomName_ = req->getParameter("room_name");
|
|
|
|
s.id_ = chatRooms_.subscribe(s.chatRoomName_,
|
|
|
|
[conn](const std::string &topic,
|
|
|
|
const std::string &message) {
|
|
|
|
conn->send(message);
|
|
|
|
});
|
|
|
|
conn->setContext(std::make_shared<Subscriber>(std::move(s)));
|
2018-11-16 05:26:14 +00:00
|
|
|
}
|