forked from PhysicsX/ExampleCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket_async_server.cpp
More file actions
108 lines (81 loc) · 2.58 KB
/
websocket_async_server.cpp
File metadata and controls
108 lines (81 loc) · 2.58 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
// g++ -std=c++17 -I /usr/include/boost -pthread websocket_async_server.cpp
class EchoWebsocket : public std::enable_shared_from_this<EchoWebsocket>
{
websocket::stream<beast::tcp_stream> ws;
beast::flat_buffer buffer;
public:
EchoWebsocket(tcp::socket&& socket)
: ws(std::move(socket))
{
}
void
run()
{
ws.async_accept(
[self{shared_from_this()}](beast::error_code ec){
if(ec){ std::cout << ec.message() << "\n"; return;}
self->echo();
});
}
void
echo()
{
ws.async_read(
buffer,
[&, self{shared_from_this()}](beast::error_code ec, std::size_t bytes_transferred)
{
if(ec == websocket::error::closed)
return;
if(ec){ std::cout << ec.message() << "\n"; return;}
ws.async_write(
buffer.data(),
[&, self](beast::error_code ec, std::size_t bytes_transferred)
{
if(ec){ std::cout << ec.message() << "\n"; return;}
buffer.consume(buffer.size());
self->echo();
});
});
}
};
class Listener : public std::enable_shared_from_this<Listener>
{
net::io_context& ioc;
tcp::acceptor acceptor;
public:
Listener(
net::io_context& ioc,
unsigned short int port
)
: ioc(ioc)
, acceptor(ioc, {net::ip::make_address("127.0.0.1"), port}){}
void
asyncAccept()
{
acceptor.async_accept(
ioc,
[self{shared_from_this()}](boost::system::error_code ec, tcp::socket socket) {
std::make_shared<EchoWebsocket>(std::move(socket))->run();
self->asyncAccept();
});
}
};
int main(int argc, char* argv[])
{
auto const port = static_cast<unsigned short>(std::atoi("8083"));
net::io_context ioc{};
std::make_shared<Listener>(ioc,port)->asyncAccept();
ioc.run();
return 0;
}