pion  5.0.6
helloserver.cpp
1 // ---------------------------------------------------------------------
2 // pion: a Boost C++ framework for building lightweight HTTP interfaces
3 // ---------------------------------------------------------------------
4 // Copyright (C) 2007-2014 Splunk Inc. (https://github.com/splunk/pion)
5 //
6 // Distributed under the Boost Software License, Version 1.0.
7 // See http://www.boost.org/LICENSE_1_0.txt
8 //
9 
10 #include <iostream>
11 #include <boost/asio.hpp>
12 #include <boost/bind.hpp>
13 #include <pion/error.hpp>
14 #include <pion/process.hpp>
15 #include <pion/tcp/server.hpp>
16 
17 using namespace std;
18 using namespace pion;
19 
20 
22 class HelloServer : public tcp::server {
23 public:
24  HelloServer(const unsigned int tcp_port) : tcp::server(tcp_port) {}
25  virtual ~HelloServer() {}
26  virtual void handle_connection(const tcp::connection_ptr& tcp_conn)
27  {
28  static const std::string HELLO_MESSAGE("Hello there!\x0D\x0A");
29  tcp_conn->set_lifecycle(pion::tcp::connection::LIFECYCLE_CLOSE); // make sure it will get closed
30  tcp_conn->async_write(boost::asio::buffer(HELLO_MESSAGE),
31  boost::bind(&pion::tcp::connection::finish, tcp_conn));
32  }
33 };
34 
35 
36 
38 int main (int argc, char *argv[])
39 {
40  static const unsigned int DEFAULT_PORT = 8080;
41 
42  // parse command line: determine port number
43  unsigned int port = DEFAULT_PORT;
44  if (argc == 2) {
45  port = strtoul(argv[1], 0, 10);
46  if (port == 0) port = DEFAULT_PORT;
47  } else if (argc != 1) {
48  std::cerr << "usage: helloserver [port]" << std::endl;
49  return 1;
50  }
51 
52  // initialize signal handlers, etc.
53  process::initialize();
54 
55  // initialize log system (use simple configuration)
56  logger main_log(PION_GET_LOGGER("helloserver"));
57  logger pion_log(PION_GET_LOGGER("pion"));
58  PION_LOG_SETLEVEL_INFO(main_log);
59  PION_LOG_SETLEVEL_INFO(pion_log);
60  PION_LOG_CONFIG_BASIC;
61 
62  try {
63 
64  // create a new server to handle the Hello TCP protocol
65  tcp::server_ptr hello_server(new HelloServer(port));
66  hello_server->start();
67  process::wait_for_shutdown();
68 
69  } catch (std::exception& e) {
70  PION_LOG_FATAL(main_log, pion::diagnostic_information(e));
71  }
72 
73  return 0;
74 }
virtual void handle_connection(const tcp::connection_ptr &tcp_conn)
Definition: helloserver.cpp:26
STL namespace.
simple TCP server that just sends "Hello there!" to each connection
Definition: helloserver.cpp:22