標籤:boost asio
情境說明
本例子支援多線程非同步處理訊息,針對每一個連結請求,建立線程處理稍後的指令,CSimpleSession::SessionThreadFunc是線程函數,async_read_some函數設定接收資料的回呼函數ContinueRead,一般情況下,read_some函數未必能夠完整的讀取用戶端發送的資料包,當然必須要指定明確的結束標誌,雙方必須規定好等接收完畢的時候,必須等待線程返回,因此在解構函式調用m_thread->join函數,等線程函數正常返回之後,關閉串連,如果沒有等待線程返回,就直接關閉串連,會導致async_read_some函數拋出異常,目前暫時沒有什麼頭緒
service.h
#ifndef QPIDPUSHMESSAGESERVICE_H
#define QPIDPUSHMESSAGESERVICE_H
#include <iostream>
#include <vector>
#include <fstream>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/function/function0.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/thread/mutex.hpp>
namespace qpid
{
class CSimpleSession : public boost::enable_shared_from_this<CSimpleSession>
{
public:
CSimpleSession(boost::asio::io_service &io_service) : m_socket(io_service)
{
m_bRunning = true;
PrepareForNextRecv();
}
~CSimpleSession()
{
m_bRunning = false;
m_thread->join();
m_socket.close();
}
void StartThread()
{
static boost::asio::ip::tcp::no_delay option(true);
m_socket.set_option(option);
m_thread.reset(new boost::thread(boost::bind(&CSimpleSession::SessionThreadFunc, this)));
}
void SessionThreadFunc()
{
while (m_bRunning)
{
if (m_bStartSetCallBackRead)
{
m_socket.async_read_some(boost::asio::buffer(m_szRecvBuffer),
boost::bind(&CSimpleSession::ContinueRead, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
m_bStartSetCallBackRead = false;
}
boost::this_thread::sleep_for(boost::chrono::milliseconds(300));
}
m_bRunning = false;
}
boost::asio::ip::tcp::socket &GetSocket()
{
return m_socket;
}
bool GetCurThreadRunningStatus()
{
return m_bRunning;
}
void PrepareForNextRecv()
{
memset(m_szRecvBuffer, 0x00, 10240);
m_strMatch = "";
m_bStartSetCallBackRead = true;
}
private:
void ContinueRead(const boost::system::error_code &error, std::size_t bytes_transferred)
{
if (error)
{
m_bRunning = false;
return;
}
m_strMatch = m_szRecvBuffer;
int nIndexOfContentLength = m_strMatch.find("Content-Length:", 0);
int indexOfEnd = m_strMatch.find("\r\n\r\n", 0);
if (nIndexOfContentLength == -1)
{
m_bRunning = false;
return;
}
std::cout << m_strMatch << std::endl;
std::string strContextLen = m_strMatch.substr(nIndexOfContentLength + 15, indexOfEnd - nIndexOfContentLength - 15);
int nContextLen = atoi(strContextLen.c_str());
if (nContextLen < m_strMatch.length())
{
//handle
m_bRunning = false;
return;
}
m_socket.async_read_some(boost::asio::buffer((m_szRecvBuffer)),
boost::bind(&CSimpleSession::ContinueRead, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
private:
boost::asio::ip::tcp::socket m_socket;
char m_szRecvBuffer[10240];
std::string m_strMatch;
bool m_bStartSetCallBackRead;
bool m_bRunning;
boost::shared_ptr<boost::thread> m_thread;
};
typedef boost::shared_ptr<CSimpleSession> CPtrSession;
class CSimpleServer
{
public:
CSimpleServer(boost::asio::io_service &io_service, boost::asio::ip::tcp::endpoint &endpoint)
:m_ioService(io_service), m_acceptor(io_service, endpoint)
{
CPtrSession newSession(new CSimpleSession(io_service));
m_vecSession.push_back(newSession);
m_acceptor.async_accept(newSession->GetSocket(),
boost::bind(&CSimpleServer::HandleAccept,
this,
newSession,
boost::asio::placeholders::error));
}
void HandleAccept(CPtrSession newSession, const boost::system::error_code &error)
{
if (error)return;
//如果Start函數進行了阻塞,只有處理完當前的串連,才會進行下一步處理串連
newSession->StartThread();
ClearHasEndConnection();
CPtrSession createNewSession(new CSimpleSession(m_ioService));
m_vecSession.push_back(createNewSession);
m_acceptor.async_accept(createNewSession->GetSocket(),
boost::bind(&CSimpleServer::HandleAccept,
this,
createNewSession,
boost::asio::placeholders::error));
}
void ClearHasEndConnection()
{
std::vector<CPtrSession>::iterator iter;
iter = m_vecSession.begin();
std::size_t count = m_vecSession.size();
std::cout << "session count:" << count << std::endl;
while (iter != m_vecSession.end())
{
if (!(*iter)->GetCurThreadRunningStatus())
{
iter->reset();
m_vecSession.erase(iter);
break;
}
iter++;
}
}
void run()
{
m_ioService.run();
}
private:
boost::asio::io_service &m_ioService;
std::vector<CPtrSession> m_vecSession;
boost::asio::ip::tcp::acceptor m_acceptor;
};
void StartListenThread();
int StartListenService();
}
#endif
service.cpp
#include <boost/thread/thread.hpp>
#include "service.h"
void qpid::StartListenThread()
{
boost::asio::io_service ioService;
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string("192.168.0.34"), 7003);
qpid::CSimpleServer s(ioService, endpoint);
s.run();
}
int qpid::StartListenService()
{
boost::thread serviceThread(&StartListenThread);
serviceThread.detach();
return 0;
}
boost 多線程非同步處理例子