ASIO网络库-Server

Server 类实现
server.h
#ifndef MYSERVER_H
#define MYSERVER_H

#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0600
#endif // !_WIN32_WINNT

#ifndef ASIO_STANDALONE
#define ASIO_STANDALONE
#endif//ASIO_STANDALONE

#include"Session.h"
#include <asio.hpp>
#include<thread>
#include<map>
class MyServer
{
public:
    MyServer();
    ~MyServer();
    void init();
    void start();
    void onStart();
    void run();
    void wait();
    void stop();
    void command();
    void removeSession(int id);
private:
    void do_accept();
    void accept_handler(Session *session, const asio::error_code &error);
private:
    asio::io_service *m_io_service;
    asio::io_service::work *m_service_work;//
    asio::ip::tcp::endpoint* m_endpoint;
    asio::ip::tcp::acceptor * m_acceptor;
    asio::ip::tcp::socket * m_socket;
    std::thread * m_thread;
    asio::error_code m_ec;

    bool m_running;
    int m_currentSessionId ;
    std::map<int, Session*> m_sessionMap;
};

#endif//M
server.cpp
#include "MyServer.h"
#include <iostream>
using namespace std;
MyServer::MyServer():m_currentSessionId(0),m_running(false)
{
    m_io_service= new asio::io_service();
    m_service_work=new asio::io_service::work(*m_io_service);
    m_endpoint=new asio::ip::tcp::endpoint(asio::ip::tcp::v4(),54545);
    m_acceptor=new asio::ip::tcp::acceptor(*m_io_service,*m_endpoint);
    m_socket=new asio::ip::tcp::socket(*m_io_service);
}
void MyServer::init(){
}
void MyServer::start(){
    m_running=true;
    m_thread = new std::thread(&MyServer::command, this);
    run();
}
void MyServer::command()
{
    int sid=0;
    char cmd[128];
    while(true){
        std::cin>>sid>>cmd;
        size_t len=std::strlen(cmd);
        cmd[len]='\0';
        if(sid==0){
            std::cout<<"stop cmd!\n";
            break;
        }else{
            Session *s=m_sessionMap.at(sid);
            if(s)   s->write(cmd);
            else    std::cout<<"fail to find session:id="<<sid<<std::endl;
        }
    }
}
void MyServer::onStart()
{
    m_acceptor->listen();
    cout<<"start listening!\n";
    do_accept();
}
void MyServer::run(){
    onStart();
    m_io_service->run();
}
void MyServer::stop(){
    m_running = false;
}
void MyServer::wait(){
    m_thread->join();
}
void MyServer::do_accept(){
    Session *session = new Session(m_io_service);

    if (session)
    {
        //async_accept(socket,fun)--每次建立连接时,新建socket
        m_acceptor->async_accept(*(session->getSocket()),std::bind(&MyServer::accept_handler, this, session, std::placeholders::_1));
    }
    else
    {
        cout<<"allocate client session failed\n";
    }

}
void MyServer::accept_handler(Session *session, const asio::error_code &error)
{
    if (session != NULL && !error)
    {
        m_currentSessionId++;
        session->setId(m_currentSessionId);
        printf("Client Session %d Connected\n", m_currentSessionId);
        m_sessionMap[m_currentSessionId] = session;
        session->read();
    }
    do_accept();
}
void MyServer::removeSession(int id){
    Session *s=m_sessionMap.at(id);
    delete s;
    m_sessionMap.erase(id);
}
MyServer::~MyServer(){
    map<int,Session*>::iterator it;
    for(it=m_sessionMap.begin();it!=m_sessionMap.end();++it){
        delete it->second;
    }
    delete m_service_work;
    delete m_io_service;

    delete m_endpoint;
    delete m_acceptor;
    delete m_socket;
}
session.h

#ifndef SESSION_H
#define SESSION_H

#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0600
#endif // !_WIN32_WINNT

#ifndef ASIO_STANDALONE
#define ASIO_STANDALONE
#endif//ASIO_STANDALONE


#include<asio.hpp>
#include<iostream>
class Session
{
public:
    explicit Session(asio::io_service* arg_ios);
    ~Session();
    void start();
    void reset();//重置会话
    void read();//异步接收消息
    void on_read(const asio::error_code &error, size_t bytes_transferred);
    void write(char * data);
    void on_write(char *data ,const asio::error_code &error, size_t bytes_transferred);
    asio::ip::tcp::socket* Session::getSocket();
    void setId(int id);
    int getId();
private:
        asio::ip::tcp::socket *m_socket;
        int m_sessionId;
        char * read_data;
};
#endif//SESSION_H
session.cpp
#include"Session.h"

Session::Session(asio::io_service* arg_ios)
{
    m_socket=new asio::ip::tcp::socket(*arg_ios);
    read_data=new char [128];
}
void Session::start()
{
}
void Session::reset(){
    m_socket->close();
}
void Session::read()
{
    m_socket->async_read_some(asio::buffer(read_data, 128),std::bind(&Session::on_read,this,std::placeholders::_1,std::placeholders::_2));
}
void Session::on_read(const asio::error_code &error, size_t bytes_transferred){
    if (error || bytes_transferred == 0)
    {
        std::cout<<"session-id:"<<getId()<<" is closed!"<<std::endl;
        return;
    }else{
        std::cout<<"session-id:"<<getId()<<" [msg]>>"<<read_data<<std::endl;
    }
    read();
}
void Session::write(char * data)
{
    m_socket->async_write_some(asio::buffer(data, 128),std::bind(&Session::on_write,this,data,std::placeholders::_1,std::placeholders::_2));
}
void Session::on_write(char *data ,const asio::error_code &error, size_t bytes_transferred)
{
    if (error || bytes_transferred == 0)
    {
        std::cout<<"session-id:"<<getId()<<" is closed!"<<std::endl;
        return;
    }else{
        std::cout<<"send-by-session-id:"<<getId()<<" [msg]>>"<<read_data<<std::endl;
    }
}
void Session::setId(int id){
    m_sessionId=id;
}
int Session::getId(){
    return m_sessionId;
}
asio::ip::tcp::socket* Session::getSocket()
{
    return m_socket;
}
Session::~Session()
{
    std::cout<<"session-"<<getId()<<" is release!\n";
}

main.cpp

#include <iostream>
#include "MyServer.h"
MyServer *s=NULL;
int main()
{
    s=new MyServer();
    s->start();
    //system("pause");
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值