Simple server built based on boost: asio Encapsulation

Source: Internet
Author: User

Simple server built based on boost: asio Encapsulation

After one day of simple learning, I tried to write a simple server by myself, which can implement the following three callback functions: onConnect onMessage onClose

Paste the code below

1. BaseServer abstract class

BaseServer. h

/* Name: BaseServeruse: the basest serverauthor: hezijian (hezijian22@163.com) */# ifdef _ MSC_VER # define _ WIN32_WINNT 0x0501 # endif # ifndef _ BASE_SERVER_H _ # define _ BASE_SERVER_H _ # include
 
  
# 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 the connection void start (); // void connect (std: shared_ptr
  
   
PSession, error_code ec); // void message (std: shared_ptr
   
    
PSession, error_code ec); // void close (std: shared_ptr
    
     
PSession, error_code ec); // The following is the callback function, which is rewritten by the subclass virtual void onConnect (std: shared_ptr
     
      
PSession, error_code ec) = 0; virtual void onMessage (std: shared_ptr
      
        PSession, error_code ec) = 0; virtual void onClose (std: shared_ptr
       
         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
 
  
BaseServer: BaseServer (io_service & iosev): m_iosev (iosev), m_acceptor (iosev, tcp: endpoint (tcp: v4 (), SERVER_CONTANT: PORT )), m_unique_id (1) {init ();} void BaseServer: init () {return;} void BaseServer: start () {std: shared_ptr
  
   
PSession (new Session (m_iosev); m_acceptor.async_accept (pSession-> getSocket (), std: bind (& BaseServer: connect, this, pSession, std: placeholders :: _ 1);} void BaseServer: connect (std: shared_ptr
   
    
PSession, error_code ec) {std: cout <"a new connection:" <pSession-> getSocket (). remote_endpoint (). address () <std: endl; onConnect (pSession, ec); if (ec) return; // continue waiting for connection start (); pSession-> getSocket (). async_read_some (buffer (pSession-> getBuf (), SERVER_CONTANT: SESSION_BUF_LEN), std: bind (& BaseServer: message, this, pSession, std: placeholders :: _ 1);} void BaseServer: message (std: shared_ptr
    
     
PSession, error_code ec) {if (ec) {BaseServer: close (pSession, ec); return;} std :: cout <"Slave client" <pSession-> getSocket (). remote_endpoint (). address () <"received data:" <pSession-> getBuf () <std: endl; onMessage (pSession, ec); // clear the buffer, continue to wait for data memset (pSession-> getBuf (), 0, sizeof (pSession-> getBuf (); pSession-> getSocket (). async_read_some (buffer (pSession-> getBuf (), SERVER_CONTANT: SESSION_BUF_LEN), std: bind (& BaseServer: message, this, pSession, std: placeholders :: _ 1);} void BaseServer: close (std: shared_ptr
     
      
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
      
        (Ec); pSession-> getSocket (). close (const_cast
       
         (Ec); onClose (pSession, ec); return ;}
       
      
     
    
   
  
 

Description: BaseServer is an abstract class. The callback function must be rewritten by the subclass to be instantiated. SERVER_CONSTANT is the management header file of the server constant.

Session is currently a class that encapsulates socket and buf, and may be modified in the future.


2. MyServer inherits 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
 
   pSession, error_code ec);virtual void onMessage(std::shared_ptr
  
    pSession, error_code ec);virtual void onClose(std::shared_ptr
   
     pSession, error_code ec);};#endif
   
  
 

MyServer. cpp

#include "MyServer.h"MyServer::MyServer(io_service& iosev):BaseServer(iosev){}void MyServer::onConnect(std::shared_ptr
 
   pSession, error_code ec){printf("onConnect\n");}void MyServer::onMessage(std::shared_ptr
  
    pSession, error_code ec){printf("onMessage\n");}void MyServer::onClose(std::shared_ptr
   
     pSession, error_code ec){printf("onClose\n");}
   
  
 


3. main Function

# Include "MyServer. h" # include
 
  
Int main (int argc, char * argv []) {try {io_service iosev; MyServer sev (iosev); // start waiting for sev connection. start (); std: cout <"server started successfully! "<Std: endl; iosev. run ();} catch (std: exception e) {std: cout <e. what () <std: endl;} return 0 ;}
 


Related Article

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.