Simple server based on the Boost::asio package

Source: Internet
Author: User

After a day of simple learning, try to write a simple server, you can achieve the following three callback functions: OnConnect onMessage OnClose

The code is posted directly below

1.BaseServer Abstract class

BaseServer.h

/*name:baseserveruse:the basest Serverauthor:hezijian ([email protected]) */#ifdef _msc_ver#define _WIN32_WINNT 0x0501#endif#ifndef _base_server_h_#define _base_server_h_#include <boost/asio.hpp> #include "Server_ CONSTANT.h "using namespace boost::asio;using boost::system::error_code;using ip::tcp;class session{public:session ( io_service& Iosev): M_buf ((char*) malloc (Server_contant::session_buf_len)), M_socket (Iosev) {memset (m_buf,0, Server_contant::session_buf_len);} ~session () {delete[] m_buf;} Inline ip::tcp::socket& Getsocket () {return m_socket;} Inline char* getbuf () {return m_buf;} Private:ip::tcp::socket m_socket;char* m_buf;}; Class Baseserver{public:baseserver (Io_service &iosev);//Initialize void init ();//wait for connection void start ();//When there is a connection void connect ( Std::shared_ptr<session> psession, Error_code EC);//When a message is delivered, void message (std::shared_ptr<session> Psession, Error_code EC);//void Close when disconnected (std::shared_ptr<session> psession, Error_code EC);//The following is a callback function, overriding virtual void Oncon by subclassesNect (std::shared_ptr<session> psession, error_code EC) =0;virtual void OnMessage (std::shared_ptr<session > psession, error_code EC) =0;virtual void OnClose (std::shared_ptr<session> psession, error_code EC) =0;private : Io_service &m_iosev;ip::tcp::acceptor m_acceptor;int m_unique_id;}; #endif

BaseServer.cpp

#include "BaseServer.h" #include <iostream>baseserver::baseserver (Io_service &iosev): M_iosev (Iosev), m_ Acceptor (Iosev, Tcp::endpoint (Tcp::v4 (), server_contant::P ort)), m_unique_id (1) {init ();} void Baseserver::init () {return;} void Baseserver::start () {std::shared_ptr<session> psession (New Session (M_iosev)); M_acceptor.async_accept ( Psession->getsocket (), Std::bind (&baseserver::connect,this, psession, std::p laceholders::_1));} void Baseserver::connect (std::shared_ptr<session> psession, Error_code EC) {Std::cout << "a New connection:" < < Psession->getsocket (). Remote_endpoint (). Address () << std::endl;onconnect (PSESSION,EC), if (EC) return ;//continue to wait for connection start ();p Session->getsocket (). Async_read_some (Buffer (Psession->getbuf (), server_contant::session _buf_len), Std::bind (&baseserver::message,this,psession,std::p laceholders::_1));} void Baseserver::message (std::shared_ptr<session> psession, Error_code EC) {if (EC) {Baseserver::close (pSession , EC); return;} Std:: cout << "from client" << psession->getsocket (). Remote_endpoint (). Address () << "received data:" << Psession->getbuf () << std::endl;onmessage (PSESSION,EC);//clear buffer, continue to wait for data memset (PSESSION-&GT;GETBUF (), 0, sizeof (PSESSION-&GT;GETBUF ()));p Session->getsocket (). Async_read_some (Buffer (PSESSION-&GT;GETBUF (), Server_ Contant::session_buf_len), Std::bind (&baseserver::message,this,psession,std::p laceholders::_1));} void Baseserver::close (std::shared_ptr<session> psession, Error_code EC) {std::cout << Boost::system:: System_error (EC). What () << std::endl;std::cout << psession->getsocket (). Remote_endpoint (). Address () << "Disconnect" << std::endl;psession->getsocket (). Shutdown (Boost::asio::ip::tcp::socket::shutdown _both, const_cast<boost::system::error_code&> (EC));p Session->getsocket (). Close (const_cast<boost  ::system::error_code&> (EC)); OnClose (PSESSION,EC); return; }

Description, Baseserver is an abstract class that must be overridden by subclasses to instantiate, and Server_constant is the management header file for server constants.

The session is temporarily a class that wraps sockets and buf, and may later be enriched with modifications


2.MyServer Inheritance Baseserver

MyServer.h

#ifndef _my_server_h_#define _my_server_h_#include "BaseServer.h" Class Myserver:public Baseserver{public:myserver ( io_service& Iosev); virtual void OnConnect (std::shared_ptr<session> psession, Error_code EC); virtual void OnMessage (std::shared_ptr<session> psession, Error_code EC); virtual void OnClose (std::shared_ptr<session > psession, Error_code EC);}; #endif

MyServer.cpp

#include "MyServer.h" Myserver::myserver (io_service& Iosev): Baseserver (Iosev) {}void myserver::onconnect (std:: Shared_ptr<session> psession, Error_code EC) {printf ("onconnect\n");} void Myserver::onmessage (std::shared_ptr<session> psession, error_code EC) {printf ("onmessage\n");} void Myserver::onclose (std::shared_ptr<session> psession, error_code EC) {printf ("onclose\n");}


3.main function

#include "MyServer.h" #include <iostream>int main (int argc, char* argv[]) {Try{io_service Iosev; MyServer SEv (Iosev);//start Waiting for connection Sev.start (); std::cout << "Server started successfully!" "<< Std::endl;iosev.run ();} catch (Std::exception e) {std::cout << e.what () << Std::endl;} return 0;}


Simple server based on the Boost::asio package

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.