Skip to content

Commit

Permalink
Using boost an asio simple encapsulate server framework
Browse files Browse the repository at this point in the history
# 使用boost asio简单封装的服务器框架
#
# 仅供学习和参考,任何偏离此意向的改动和使用与作者无关
#
# 目录src中为服务器源码
# 目录client中为简易测试客户端源码
# 代码依赖于boost库,在进行编译前请确保已安装boost,作者在boost-1.55中进行开发和简单测试
# 代码支持windows和linux平台,windows请自行新建工程并配置头文件路径和库文件路径
#
# 在已安装boost的情况下:
1.修改Makefile中
16行 INCLUDES 路径
19行 LIBS路径 为相应boost的库文件和头文件路径

2.执行make,即可在当前目录生成Server文件

3.服务启动的地址和端口在main.cpp写死,编译前请自行修改为相应的地址和端口

ps:欢迎大家吐槽和交流,本人CSDN:fly2010love
  • Loading branch information
yuanqinguo committed May 6, 2015
1 parent ec9d10d commit 4540bb1
Show file tree
Hide file tree
Showing 14 changed files with 659 additions and 0 deletions.
21 changes: 21 additions & 0 deletions READEM.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# boost asio Server framework
# ʹ��boost asio�򵥷�װ�ķ��������
#
# ����ѧϰ�Ͳο����κ�ƫ�������ĸĶ���ʹ���������޹�
#
# Ŀ¼src��Ϊ������Դ��
# Ŀ¼client��Ϊ���ײ��Կͻ���Դ��
# ����������boost�⣬�ڽ��б���ǰ��ȷ���Ѱ�װboost��������boost-1.55�н��п����ͼ򵥲���
# ����֧��windows��linuxƽ̨��windows�������½����̲�����ͷ�ļ�·���Ϳ��ļ�·��
#
# ���Ѱ�װboost������£�
1.�޸�Makefile��
16�� INCLUDES ·��
19�� LIBS·�� Ϊ��Ӧboost�Ŀ��ļ���ͷ�ļ�·��

2.ִ��make�������ڵ�ǰĿ¼����Server�ļ�

3.���������ĵ�ַ�Ͷ˿���main.cppд��������ǰ�������޸�Ϊ��Ӧ�ĵ�ַ�Ͷ˿�


ps����ӭ����²ۺͽ���������CSDN��fly2010love
Binary file added client/Client
Binary file not shown.
31 changes: 31 additions & 0 deletions client/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#bash/bin

TOPDIR=.

TARGE=Client

SRCS = $(wildcard *.cpp)
OBJS = $(SRCS:.cpp = .o)
CC = g++

#dirs := Kmp buf
#all:
# $(foreach N,$(dirs),$(make -C $(N)))

#include header
INCLUDES = -I/home/boostlib/include

#include lib path
LIBS = -L/home/boostlib/lib
LDLIBS = -lboost_system -lboost_thread -lpthread

CCFLAGS = -g -Wall

$(TARGE):$(OBJS)
$(CC) $^ -o $@ $(INCLUDES) $(LIBS) $(LDLIBS) $(CCFLAGS)

%.o:%.cpp
$(CC) -c $< $(CCFLAGS)

clean:
rm *.o $(TARGE)
48 changes: 48 additions & 0 deletions client/client.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;

enum { max_length = 1024 };

int main(int argc, char* argv[])
{
//try
{
boost::asio::io_service io_service;

tcp::resolver resolver(io_service);
tcp::resolver::query query(tcp::v4(), "192.168.199.146", "12345");
tcp::resolver::iterator iterator = resolver.resolve(query);

while(1)
{
tcp::socket s(io_service);
boost::asio::connect(s, iterator);
boost::system::error_code gnoredErr;
s.shutdown(boost::asio::ip::tcp::socket::shutdown_both, gnoredErr);
}

// using namespace std; // For strlen.
// std::cout << "Enter message: ";
// char request[max_length];
// std::cin.getline(request, max_length);
// size_t request_length = strlen(request);
// boost::asio::write(s, boost::asio::buffer(request, request_length));

// char reply[max_length];
// size_t reply_length = boost::asio::read(s,
// boost::asio::buffer(reply, request_length));
// std::cout << "Reply is: ";
// std::cout.write(reply, reply_length);
// std::cout << "\n";
}
//catch (std::exception& e)
{
//std::cerr << "Exception: " << e.what() << "\n";
}

return 0;
}
62 changes: 62 additions & 0 deletions src/AsioPool.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#include "AsioPool.h"

#include <stdexcept>
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>

AsioPool::AsioPool(int iPoolSize)
{
m_ioIndex = 0;
if (iPoolSize <= 0)
{
iPoolSize = 1;
}

for (int i=0; i<iPoolSize; i++)
{
IOServicePtr ioservice(new boost::asio::io_service);
IOWorkPtr iowork(new boost::asio::io_service::work(*ioservice));

m_ioServicePtrs.push_back(ioservice);
m_ioWorkPtrs.push_back(iowork);
}
}

void AsioPool::OnRun()
{
typedef boost::shared_ptr<boost::thread> threadPtr;
std::vector<threadPtr> threads;
size_t i,j;

for (i=0; i<m_ioServicePtrs.size(); i++)
{
threadPtr thread(new boost::thread(
boost::bind(&boost::asio::io_service::run, m_ioServicePtrs.at(i)) ) );

threads.push_back(thread);
}

for (j=0; j<threads.size(); j++)
{
threads.at(j)->join();
}
}

void AsioPool::OnStop()
{
size_t i;
for (i=0; i<m_ioServicePtrs.size(); i++)
{
m_ioServicePtrs.at(i)->stop();
}
}

boost::asio::io_service& AsioPool::GetIoService()
{
boost::asio::io_service& service = *m_ioServicePtrs.at(m_ioIndex);
if (++m_ioIndex >= m_ioServicePtrs.size())
{
m_ioIndex = 0;
}
return service;
}
33 changes: 33 additions & 0 deletions src/AsioPool.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#ifndef ASIOPOOL_H_
#define ASIOPOOL_H_

#include <boost/asio.hpp>
#include <vector>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>


class AsioPool
:private boost::noncopyable
{
public:
AsioPool(int iPoolSize);

void OnRun();

void OnStop();

boost::asio::io_service& GetIoService();
protected:

private:
typedef boost::shared_ptr<boost::asio::io_service> IOServicePtr;
typedef boost::shared_ptr<boost::asio::io_service::work> IOWorkPtr;

std::vector<IOServicePtr> m_ioServicePtrs;
std::vector<IOWorkPtr> m_ioWorkPtrs;

size_t m_ioIndex;
};

#endif//ASIOPOOL_H_
141 changes: 141 additions & 0 deletions src/Connection.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
#include <boost/bind.hpp>
#include <iostream>

#include "Connection.h"

Connection::Connection(boost::asio::io_service& ioservice, boost::asio::io_service& work_service,
RequestHandler& ReqHandler)
: m_socket(ioservice)
, m_work_service(work_service)
, m_work_strand(work_service)
, m_ReqHandler(ReqHandler)
{
m_recvCacheBufPtr.reset(new std::vector<char>);
}

void Connection::OnStart()
{
boost::system::error_code gnoredErr;
m_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, gnoredErr);
// m_socket.async_read_some(boost::asio::buffer(m_Buffers),
// boost::bind(&Connection::HandleRead, shared_from_this(),
// boost::asio::placeholders::error,
// boost::asio::placeholders::bytes_transferred));

}

boost::asio::ip::tcp::socket& Connection::GetSocket()
{
return m_socket;
}


void Connection::HandleRead(const boost::system::error_code& errCode, std::size_t bytes_transferred)
{
if (!errCode)
{
int iret = 0;
//m_ReqHandler,处理请求,比如登录等等
if (!iret)
{
std::string timeStr;
GetCurrentStringTime(timeStr);

std::cout<<timeStr<<"::Connection::HandleRead::data = " << m_Buffers.data()<<std::endl;
/*m_recvCacheBufPtr->resize(m_recvCacheBufPtr->size() + bytes_transferred);
std::copy(m_Buffers.begin(), m_Buffers.begin() + bytes_transferred,
(m_recvCacheBufPtr->begin() + m_recvCacheBufPtr->size()));*/

std::string reply = "Wirte";//回复OK

boost::asio::async_write(m_socket, boost::asio::buffer(reply),
boost::bind(&Connection::HandleWirte, shared_from_this(),
boost::asio::placeholders::error));
//m_work_strand.post(boost::bind(&Connection::HandleReadDone
// , shared_from_this(), errCode));

// boost::asio::streambuf request;
// std::ostream request_stream(&request);
// request_stream << "Accept: */*\r\n";
// request_stream << "Connection: close\r\n\r\n";

// Send the request.
//boost::asio::write(m_socket, request);

}
else if (-1 == iret)
{
m_socket.async_read_some(boost::asio::buffer(m_Buffers),
boost::bind(&Connection::HandleRead, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
//else
//{
// std::string reply;//回复失败
// boost::asio::async_write(m_socket, boost::asio::buffer(reply),
// boost::bind(&Connection::HandleWirte, shared_from_this(),
// boost::asio::placeholders::error));
//}
}
else
{
std::string timeStr;
GetCurrentStringTime(timeStr);
std::cout<<timeStr<<"::Connection::HandleRead::Error shutdown" <<std::endl;
boost::system::error_code gnoredErr;
m_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, gnoredErr);
}
}

void Connection::HandleWirte(const boost::system::error_code& errCode)
{
//if (!errCode)
//{
// std::string timeStr;
// GetCurrentStringTime(timeStr);
// std::cout<<timeStr<<"::Connection::HandleWirte::write done" <<std::endl;
// m_socket.async_read_some(boost::asio::buffer(m_Buffers),
// boost::bind(&Connection::HandleRead, shared_from_this(),
// boost::asio::placeholders::error,
// boost::asio::placeholders::bytes_transferred));
// ////是否有其他需要处理,没有直接断掉链接
// //boost::system::error_code gnoredErr;
// //m_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, gnoredErr);
//}
//else
if(!errCode)
{
std::string timeStr;
GetCurrentStringTime(timeStr);
std::cout<<timeStr<<"::Connection::HandleWirte::Wirte Done!!! shutdown socket" <<std::endl;
boost::system::error_code gnoredErr;
m_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, gnoredErr);
}
else
{
std::string timeStr;
GetCurrentStringTime(timeStr);
std::cout<<timeStr<<"::Connection::HandleWirte::Wirte Error!!! shutdown socket" <<std::endl;
}

boost::system::error_code gnoredErr;
m_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, gnoredErr);
}

void Connection::HandleReadDone(const boost::system::error_code& errCode)
{
if(!errCode)
{
std::string timeStr;
GetCurrentStringTime(timeStr);
std::string recvStr(m_recvCacheBufPtr->begin(), m_recvCacheBufPtr->end());
std::cout<<timeStr<<"::Connection::HandleReadDone::m_recvCacheBufPtr = " << recvStr.c_str()<<std::endl;

std::string reply = "Wirte";//回复OK

boost::asio::async_write(m_socket, boost::asio::buffer(reply),
boost::bind(&Connection::HandleWirte, shared_from_this(),
boost::asio::placeholders::error));
}
}
Loading

0 comments on commit 4540bb1

Please sign in to comment.