pion-net  4.0.9
PionHelloServer.cpp
1 // ------------------------------------------------------------------
2 // pion-net: a C++ framework for building lightweight HTTP interfaces
3 // ------------------------------------------------------------------
4 // Copyright (C) 2007-2008 Atomic Labs, Inc. (http://www.atomiclabs.com)
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/net/TCPServer.hpp>
14 #include "ShutdownManager.hpp"
15 
16 using namespace std;
17 using namespace pion;
18 using namespace pion::net;
19 
20 
22 class HelloServer : public TCPServer {
23 public:
24  HelloServer(const unsigned int tcp_port) : TCPServer(tcp_port) {}
25  virtual ~HelloServer() {}
26  virtual void handleConnection(TCPConnectionPtr& tcp_conn)
27  {
28  static const std::string HELLO_MESSAGE("Hello there!\x0D\x0A");
29  tcp_conn->setLifecycle(TCPConnection::LIFECYCLE_CLOSE); // make sure it will get closed
30  tcp_conn->async_write(boost::asio::buffer(HELLO_MESSAGE),
31  boost::bind(&TCPConnection::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: PionHelloServer [port]" << std::endl;
49  return 1;
50  }
51 
52  // setup signal handler
53 #ifdef PION_WIN32
54  SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
55 #else
56  signal(SIGINT, handle_signal);
57 #endif
58 
59  // initialize log system (use simple configuration)
60  PionLogger main_log(PION_GET_LOGGER("PionHelloServer"));
61  PionLogger pion_log(PION_GET_LOGGER("pion"));
62  PION_LOG_SETLEVEL_INFO(main_log);
63  PION_LOG_SETLEVEL_INFO(pion_log);
64  PION_LOG_CONFIG_BASIC;
65 
66  try {
67 
68  // create a new server to handle the Hello TCP protocol
69  TCPServerPtr hello_server(new HelloServer(port));
70  hello_server->start();
71  main_shutdown_manager.wait();
72 
73  } catch (std::exception& e) {
74  PION_LOG_FATAL(main_log, e.what());
75  }
76 
77  return 0;
78 }
virtual void handleConnection(TCPConnectionPtr &tcp_conn)
simple TCP server that just sends "Hello there!" to each connection