-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathpushcpp.cpp
83 lines (70 loc) · 1.6 KB
/
pushcpp.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
#include "pushcpp_internal.h"
pushcpp::pushcpp(
const string &appKey,
ConnectionEventHandler ch,
ErrorEventHandler eh
)
{
this->m_connectionEventHandler = ch;
this->m_errorEventHandler = eh;
stringstream str;
str << "ws://ws.pusherapp.com:80/app/";
str << appKey;
str << "?client=pushcpp&version=1.0&protocol=5";
m_url = str.str();
}
void pushcpp::connect()
{
DEBUG("Connecting.");
assert(!this->m_eventThread);
m_eventThread = new thread(&pushcpp::EventThread, this);
assert(this->m_eventThread);
}
bool pushcpp::connected() const
{
return
this->m_websocket != NULL && (
((WebSocket::pointer) this->m_websocket)->
getReadyState() == WebSocket::OPEN
);
}
void pushcpp::disconnect(bool wait)
{
m_wantDisconnect = true;
if (wait && m_eventThread)
m_eventThread->join();
}
void pushcpp::join()
{
assert(this->m_eventThread);
DEBUG("joining!");
m_eventThread->join();
}
bool pushcpp::sendRaw(const string &raw)
{
WebSocket::pointer ws = (WebSocket::pointer) this->m_websocket;
if (ws != NULL && ws->getReadyState() == WebSocket::OPEN) {
DEBUG("send: %s", raw.c_str());
ws->send(raw);
return true;
}
return false;
}
bool pushcpp::send(
const string &channel,
const string &event,
const string &data
)
{
json_t *json = json_object();
json_object_set_new(json, "event", json_string(event.c_str()));
if (channel != "")
json_object_set_new(json, "channel", json_string(channel.c_str()));
json_object_set_new(json, "data", json_string(data.c_str()));
char *dumped = json_dumps(json, 0);
assert(dumped);
json_decref(json);
bool ret = sendRaw(dumped);
free(dumped);
return ret;
}