#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include "Session.h"
using namespace boost::asio::ip;
using namespace boost::asio;
class Acceptor
{
public:
typedef boost::shared_ptr<Session> SessionPtr;
public:
Acceptor(io_service& ioservice, tcp::endpoint& endpoint);
~Acceptor();
private:
void handle_accept(const boost::system::error_code& error, SessionPtr session);
private:
io_service& ioservice_;
tcp::acceptor acceptor_;
};
#include "stdafx.h"
#include "Acceptor.h"
Acceptor::Acceptor(boost::asio::io_service& ioservice, tcp::endpoint& endpoint) :
ioservice_(ioservice),
acceptor_(ioservice, endpoint)
{
SessionPtr new_session(new Session(ioservice));
acceptor_.async_accept(new_session->socket(),
boost::bind(&Acceptor::handle_accept, this, boost::asio::placeholders::error, new_session));
}
Acceptor::~Acceptor()
{
}
void Acceptor::handle_accept(const boost::system::error_code& error, SessionPtr session)
{
if (!error)
{
std::cout << "get a new client!" << std::endl; //实现对每个客户端的数据处理
session->start();
SessionPtr new_session(new Session(ioservice_));
acceptor_.async_accept(new_session->socket(),
boost::bind(&Acceptor::handle_accept, this, boost::asio::placeholders::error, new_session));
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/smart_ptr.hpp>
#define max_len 1024
using namespace boost::asio::ip;
class Session : public boost::enable_shared_from_this<Session>
{
public:
Session(boost::asio::io_service& ioservice);
~Session();
tcp::socket& socket();
void start();
private:
void handle_write(const boost::system::error_code& error);
void handle_read(const boost::system::error_code& error);
private:
tcp::socket m_socket;
char data_[max_len];
};
posted on 2009-08-19 00:21
小王 阅读(1355)
评论(0) 编辑 收藏 引用 所属分类:
网络通讯