1. 服务器端
server.h
#include <boost/asio.hpp>
#include <boost/array.hpp>
using boost::asio::ip::tcp;
using namespace boost::asio;
#include <memory>
#include <utility>
#include <vector>
#include <ctime>
#include <iostream>
// A reference-counted non-modifiable buffer class.
//buffer类,用来保存要发送的消息。
class shared_const_buffer
{
public:
// Construct from a std::string.
explicit shared_const_buffer(const std::string& data)
: data_(new std::vector<char>(data.begin(), data.end())),
buffer_(boost::asio::buffer(*data_))
{
}
// Implement the ConstBufferSequence requirements.
typedef boost::asio::const_buffer value_type;
typedef const boost::asio::const_buffer* const_iterator;
const boost::asio::const_buffer* begin() const { return &buffer_; }
const boost::asio::const_buffer* end() const { return &buffer_ + 1; }
private:
std::shared_ptr<std::vector<char> > data_;
boost::asio::const_buffer buffer_;
};
//处理socket
class Session:public std::enable_shared_from_this<Session>
{
public:
Session(tcp::socket socket) :
m_socket(std::move(socket)){}
void start(){
std::cout << "connect" << std::endl;
do_write(); //框架内部,可修改问其他服务器的功能。
}
private:
void do_write(){
std::time_t now = std::time(0);
shared_const_buffer buffer(std::ctime(&now));
auto self(shared_from_this());
boost::asio::async_write(m_socket, buffer,
[this, self](boost::system::error_code /*ec*/, std::size_t /*length*/)
{
});
}
private:
tcp::socket m_socket;
};
//服务器主程序,循环异步分发socket事件。
class Server
{
public:
Server(io_service &ios, short port) :
m_acceptor(ios, tcp::endpoint(tcp::v4(), port)),
m_socket(ios)
{
do_accept();
}
private:
void do_accept(){
m_acceptor.async_accept(m_socket,
[this](boost::system::error_code ec){
if (!ec){
std::make_shared<Session>(std::move(m_socket))->start();
}
do_accept(); //循环
});
}
private:
tcp::socket m_socket;
tcp::acceptor m_acceptor;
};
main.cpp
#include <boost/asio.hpp>
using namespace boost::asio;
#include "server.h"
int main()
{
io_service ios;
int port = 6677;
Server server(ios, port);
ios.run();
return 0;
}
2. 客户端
main.cpp
//stl
#include <iostream>
//boost
#include <boost/asio.hpp>
#include <boost/array.hpp>
int main(int argc, char **argv)
{
boost::asio::io_service ios;
boost::asio::ip::tcp::socket socket(ios);
//连接
boost::asio::ip::tcp::resolver resolver(ios);
auto endpoint_iterator = resolver.resolve({ "127.0.0.1", "6677" });
boost::asio::connect(socket, endpoint_iterator);
for (;;){
boost::array<char, 128> buf;
boost::system::error_code error;
size_t len = socket.read_some(boost::asio::buffer(buf), error); //读取数据
if (error == boost::asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
std::cout.write(buf.data(), len);
}
}