forked from fkie/async_web_server_cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket_connection.cpp
95 lines (84 loc) · 2.42 KB
/
websocket_connection.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include "async_web_server_cpp/websocket_connection.hpp"
#include <boost/bind.hpp>
#include <boost/make_shared.hpp>
#include <limits>
namespace async_web_server_cpp
{
WebsocketConnection::WebsocketConnection(HttpConnectionPtr connection)
: connection_(connection)
{
}
void WebsocketConnection::set_message_handler(MessageHandler& handler)
{
handler_ = handler;
}
bool WebsocketConnection::sendTextMessage(const std::string& content)
{
async_web_server_cpp::WebsocketMessage m;
m.type = async_web_server_cpp::WebsocketMessage::type_text;
m.content = content;
return sendMessage(m);
}
bool WebsocketConnection::sendPingMessage(const std::string& content)
{
async_web_server_cpp::WebsocketMessage m;
m.type = async_web_server_cpp::WebsocketMessage::type_ping;
m.content = content;
return sendMessage(m);
}
bool WebsocketConnection::sendMessage(const WebsocketMessage& message)
{
WebsocketFrame frame;
if (frame.fromMessage(message))
{
return sendFrame(frame);
}
return false;
}
bool WebsocketConnection::sendFrame(WebsocketFrame& frame)
{
std::vector<unsigned char> buffer;
if (frame.serialize(buffer))
{
connection_->write_and_clear(buffer);
return true;
}
return false;
}
void WebsocketConnection::static_handle_read(
WebsocketConnectionWeakPtr weak_this, const char* begin, const char* end)
{
WebsocketConnectionPtr _this = weak_this.lock();
if (_this)
_this->handle_read(begin, end);
}
void WebsocketConnection::handle_read(const char* begin, const char* end)
{
boost::tribool frame_result;
const char* parse_end = begin;
while (parse_end < end)
{
boost::tie(frame_result, parse_end) =
frame_parser_.parse(frame_, parse_end, end);
if (frame_result)
{
frame_parser_.reset();
boost::tribool message_result =
frame_buffer_.consume(message_, frame_);
if (message_result)
{
if (handler_)
handler_(message_);
}
}
else if (!frame_result)
{
frame_parser_.reset();
message_.type = WebsocketMessage::type_unknown;
}
}
WebsocketConnectionWeakPtr this_weak(shared_from_this());
connection_->async_read(boost::bind(
&WebsocketConnection::static_handle_read, this_weak, _1, _2));
}
} // namespace async_web_server_cpp