pion-net
4.0.9
|
00001 // ------------------------------------------------------------------ 00002 // pion-net: a C++ framework for building lightweight HTTP interfaces 00003 // ------------------------------------------------------------------ 00004 // Copyright (C) 2007-2008 Atomic Labs, Inc. (http://www.atomiclabs.com) 00005 // 00006 // Distributed under the Boost Software License, Version 1.0. 00007 // See http://www.boost.org/LICENSE_1_0.txt 00008 // 00009 00010 #include <iostream> 00011 #include <boost/asio.hpp> 00012 #include <boost/bind.hpp> 00013 #include <pion/net/TCPServer.hpp> 00014 #include "ShutdownManager.hpp" 00015 00016 using namespace std; 00017 using namespace pion; 00018 using namespace pion::net; 00019 00020 00022 class HelloServer : public TCPServer { 00023 public: 00024 HelloServer(const unsigned int tcp_port) : TCPServer(tcp_port) {} 00025 virtual ~HelloServer() {} 00026 virtual void handleConnection(TCPConnectionPtr& tcp_conn) 00027 { 00028 static const std::string HELLO_MESSAGE("Hello there!\x0D\x0A"); 00029 tcp_conn->setLifecycle(TCPConnection::LIFECYCLE_CLOSE); // make sure it will get closed 00030 tcp_conn->async_write(boost::asio::buffer(HELLO_MESSAGE), 00031 boost::bind(&TCPConnection::finish, tcp_conn)); 00032 } 00033 }; 00034 00035 00036 00038 int main (int argc, char *argv[]) 00039 { 00040 static const unsigned int DEFAULT_PORT = 8080; 00041 00042 // parse command line: determine port number 00043 unsigned int port = DEFAULT_PORT; 00044 if (argc == 2) { 00045 port = strtoul(argv[1], 0, 10); 00046 if (port == 0) port = DEFAULT_PORT; 00047 } else if (argc != 1) { 00048 std::cerr << "usage: PionHelloServer [port]" << std::endl; 00049 return 1; 00050 } 00051 00052 // setup signal handler 00053 #ifdef PION_WIN32 00054 SetConsoleCtrlHandler(console_ctrl_handler, TRUE); 00055 #else 00056 signal(SIGINT, handle_signal); 00057 #endif 00058 00059 // initialize log system (use simple configuration) 00060 PionLogger main_log(PION_GET_LOGGER("PionHelloServer")); 00061 PionLogger pion_log(PION_GET_LOGGER("pion")); 00062 PION_LOG_SETLEVEL_INFO(main_log); 00063 PION_LOG_SETLEVEL_INFO(pion_log); 00064 PION_LOG_CONFIG_BASIC; 00065 00066 try { 00067 00068 // create a new server to handle the Hello TCP protocol 00069 TCPServerPtr hello_server(new HelloServer(port)); 00070 hello_server->start(); 00071 main_shutdown_manager.wait(); 00072 00073 } catch (std::exception& e) { 00074 PION_LOG_FATAL(main_log, e.what()); 00075 } 00076 00077 return 0; 00078 }