Skip to content

Commit 3e8dbf7

Browse files
author
Peter Thorson
committed
Add example demonstrating external io_service
1 parent 3c77ce3 commit 3e8dbf7

6 files changed

Lines changed: 228 additions & 2 deletions

File tree

SConstruct

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,11 @@ elif os.environ.has_key('BOOST_INCLUDES') and os.environ.has_key('BOOST_LIBS'):
3434
else:
3535
raise SCons.Errors.UserError, "Neither BOOST_ROOT, nor BOOST_INCLUDES + BOOST_LIBS was set!"
3636

37+
## Custom OpenSSL
38+
if os.environ.has_key('OPENSSL_PATH'):
39+
env.Append(CPPPATH = os.path.join(os.environ['OPENSSL_PATH'], 'include'))
40+
env.Append(LIBPATH = os.environ['OPENSSL_PATH'])
41+
3742
if os.environ.has_key('WSPP_ENABLE_CPP11'):
3843
env['WSPP_ENABLE_CPP11'] = True
3944
else:
@@ -93,8 +98,7 @@ if env['PLATFORM'].startswith('win'):
9398
#env['LIBPATH'] = env['BOOST_LIBS']
9499
pass
95100
else:
96-
env['LIBPATH'] = ['/usr/lib',
97-
'/usr/local/lib'] #, env['BOOST_LIBS']
101+
env.Append(LIBPATH = ['/usr/lib', '/usr/local/lib'])
98102

99103
# Compiler specific warning flags
100104
if env['CXX'].startswith('g++'):
@@ -260,6 +264,9 @@ subprotocol_server = SConscript('#/examples/subprotocol_server/SConscript',varia
260264
# telemetry_server
261265
telemetry_server = SConscript('#/examples/telemetry_server/SConscript',variant_dir = builddir + 'telemetry_server',duplicate = 0)
262266

267+
# external_io_service
268+
external_io_service = SConscript('#/examples/external_io_service/SConscript',variant_dir = builddir + 'external_io_service',duplicate = 0)
269+
263270
if not env['PLATFORM'].startswith('win'):
264271
# iostream_server
265272
iostream_server = SConscript('#/examples/iostream_server/SConscript',variant_dir = builddir + 'iostream_server',duplicate = 0)

changelog.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ HEAD
1515
`pass_through` error type.
1616
- Improvement: Add a `get_transport_error` method to Asio transport connections
1717
to allow retrieving a machine readable native transport error.
18+
- Documentation: Adds an example demonstrating the use of external `io_service`
1819
- Bug: Fix memory leak when init_asio produces an error. #454 Thank you Mark
1920
Grimes for reporting and fixing.
2021
- Bug: Fix crash when processing a specially crafted HTTP header. Thank you Eli
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
2+
file (GLOB SOURCE_FILES *.cpp)
3+
file (GLOB HEADER_FILES *.hpp)
4+
5+
init_target (external_io_service)
6+
7+
build_executable (${TARGET_NAME} ${SOURCE_FILES} ${HEADER_FILES})
8+
9+
link_boost ()
10+
final_target ()
11+
12+
set_target_properties(${TARGET_NAME} PROPERTIES FOLDER "examples")
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
## Main development example
2+
##
3+
4+
Import('env')
5+
Import('env_cpp11')
6+
Import('boostlibs')
7+
Import('platform_libs')
8+
Import('polyfill_libs')
9+
10+
env = env.Clone ()
11+
env_cpp11 = env_cpp11.Clone ()
12+
13+
prgs = []
14+
15+
# if a C++11 environment is available build using that, otherwise use boost
16+
if env_cpp11.has_key('WSPP_CPP11_ENABLED'):
17+
ALL_LIBS = boostlibs(['system'],env_cpp11) + [platform_libs] + [polyfill_libs]
18+
prgs += env_cpp11.Program('external_io_service', ["external_io_service.cpp"], LIBS = ALL_LIBS)
19+
else:
20+
ALL_LIBS = boostlibs(['system'],env) + [platform_libs] + [polyfill_libs]
21+
prgs += env.Program('external_io_service', ["external_io_service.cpp"], LIBS = ALL_LIBS)
22+
23+
Return('prgs')
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/*
2+
* Copyright (c) 2015, Peter Thorson. All rights reserved.
3+
*
4+
* Redistribution and use in source and binary forms, with or without
5+
* modification, are permitted provided that the following conditions are met:
6+
* * Redistributions of source code must retain the above copyright
7+
* notice, this list of conditions and the following disclaimer.
8+
* * Redistributions in binary form must reproduce the above copyright
9+
* notice, this list of conditions and the following disclaimer in the
10+
* documentation and/or other materials provided with the distribution.
11+
* * Neither the name of the WebSocket++ Project nor the
12+
* names of its contributors may be used to endorse or promote products
13+
* derived from this software without specific prior written permission.
14+
*
15+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18+
* ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON BE LIABLE FOR ANY
19+
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20+
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21+
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22+
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23+
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24+
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25+
*/
26+
27+
#include "tcp_echo_server.hpp"
28+
29+
#include <websocketpp/config/asio_no_tls.hpp>
30+
#include <websocketpp/server.hpp>
31+
32+
#include <iostream>
33+
34+
using websocketpp::lib::placeholders::_1;
35+
using websocketpp::lib::placeholders::_2;
36+
using websocketpp::lib::bind;
37+
38+
typedef websocketpp::server<websocketpp::config::asio> ws_echo_server;
39+
40+
// Define a callback to handle incoming messages
41+
void on_message(ws_echo_server* s, websocketpp::connection_hdl hdl, ws_echo_server::message_ptr msg) {
42+
std::cout << "on_message called with hdl: " << hdl.lock().get()
43+
<< " and message: " << msg->get_payload()
44+
<< std::endl;
45+
46+
// check for a special command to instruct the server to stop listening so
47+
// it can be cleanly exited.
48+
if (msg->get_payload() == "stop-listening") {
49+
s->stop_listening();
50+
return;
51+
}
52+
53+
try {
54+
s->send(hdl, msg->get_payload(), msg->get_opcode());
55+
} catch (websocketpp::lib::error_code const & e) {
56+
std::cout << "Echo failed because: " << e
57+
<< "(" << e.message() << ")" << std::endl;
58+
}
59+
}
60+
61+
int main() {
62+
asio::io_service service;
63+
64+
// Add a TCP echo server on port 9003
65+
tcp_echo_server custom_http_server(service, 9003);
66+
67+
// Add a WebSocket echo server on port 9002
68+
ws_echo_server ws_server;
69+
ws_server.set_access_channels(websocketpp::log::alevel::all);
70+
ws_server.clear_access_channels(websocketpp::log::alevel::frame_payload);
71+
72+
// The only difference in this code between an internal and external
73+
// io_service is the different constructor to init_asio
74+
ws_server.init_asio(&service);
75+
76+
// Register our message handler
77+
ws_server.set_message_handler(bind(&on_message,&ws_server,::_1,::_2));
78+
ws_server.listen(9002);
79+
ws_server.start_accept();
80+
81+
// TODO: add a timer?
82+
83+
// Start the Asio io_service run loop for all
84+
service.run();
85+
}
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
/*
2+
* Copyright (c) 2015, Peter Thorson. All rights reserved.
3+
*
4+
* Redistribution and use in source and binary forms, with or without
5+
* modification, are permitted provided that the following conditions are met:
6+
* * Redistributions of source code must retain the above copyright
7+
* notice, this list of conditions and the following disclaimer.
8+
* * Redistributions in binary form must reproduce the above copyright
9+
* notice, this list of conditions and the following disclaimer in the
10+
* documentation and/or other materials provided with the distribution.
11+
* * Neither the name of the WebSocket++ Project nor the
12+
* names of its contributors may be used to endorse or promote products
13+
* derived from this software without specific prior written permission.
14+
*
15+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18+
* ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON BE LIABLE FOR ANY
19+
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20+
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21+
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22+
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23+
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24+
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25+
*/
26+
27+
/**
28+
* TCP Echo Server
29+
*
30+
* This file defines a simple TCP Echo Server. It is adapted from the Asio
31+
* example: cpp03/echo/async_tcp_echo_server.cpp
32+
*/
33+
34+
#include <websocketpp/common/asio.hpp>
35+
#include <websocketpp/common/memory.hpp>
36+
#include <websocketpp/common/functional.hpp>
37+
38+
using websocketpp::lib::placeholders::_1;
39+
using websocketpp::lib::placeholders::_2;
40+
using websocketpp::lib::bind;
41+
42+
namespace asio = websocketpp::lib::asio;
43+
using tcp = asio::ip::tcp;
44+
45+
struct tcp_echo_session : websocketpp::lib::enable_shared_from_this<tcp_echo_session> {
46+
typedef websocketpp::lib::shared_ptr<tcp_echo_session> ptr;
47+
48+
tcp_echo_session(asio::io_service & service) : m_socket(service) {}
49+
50+
void start() {
51+
m_socket.async_read_some(asio::buffer(m_buffer, sizeof(m_buffer)),
52+
websocketpp::lib::bind(
53+
&tcp_echo_session::handle_read, shared_from_this(), _1, _2));
54+
}
55+
56+
void handle_read(const asio::error_code & ec, size_t transferred) {
57+
if (!ec) {
58+
asio::async_write(m_socket,
59+
asio::buffer(m_buffer, transferred),
60+
bind(&tcp_echo_session::handle_write, shared_from_this(), _1));
61+
}
62+
}
63+
64+
void handle_write(const asio::error_code & ec) {
65+
if (!ec) {
66+
m_socket.async_read_some(asio::buffer(m_buffer, sizeof(m_buffer)),
67+
bind(&tcp_echo_session::handle_read, shared_from_this(), _1, _2));
68+
}
69+
}
70+
71+
tcp::socket m_socket;
72+
char m_buffer[1024];
73+
};
74+
75+
struct tcp_echo_server {
76+
tcp_echo_server(asio::io_service & service, short port)
77+
: m_service(service)
78+
, m_acceptor(service, tcp::endpoint(tcp::v6(), port))
79+
{
80+
this->start_accept();
81+
}
82+
83+
void start_accept() {
84+
tcp_echo_session::ptr new_session(new tcp_echo_session(m_service));
85+
m_acceptor.async_accept(new_session->m_socket,
86+
bind(&tcp_echo_server::handle_accept, this, new_session, _1));
87+
}
88+
89+
void handle_accept(tcp_echo_session::ptr new_session, const asio::error_code & ec) {
90+
if (!ec) {
91+
new_session->start();
92+
}
93+
start_accept();
94+
}
95+
96+
asio::io_service & m_service;
97+
tcp::acceptor m_acceptor;
98+
};

0 commit comments

Comments
 (0)