#pragma once
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
using namespace boost::asio::ip;
using namespace boost::asio;
class Client
{
public:
//boost::shared_ptr<Client> ClientPtr;
public:
Client(boost::asio::io_service& io_service, tcp::endpoint& endpoint);
~Client();
private:
void handle_connect(const boost::system::error_code& error);
void handle_read(const boost::system::error_code& error);
void handle_write(const boost::system::error_code& error);
private:
tcp::socket socket_;
char getBuffer[1024];
};
#include "stdafx.h"
#include "Client.h"
Client::Client(boost::asio::io_service& io_service, tcp::endpoint& endpoint):
socket_(io_service)
{
socket_.async_connect(endpoint, boost::bind(&Client::handle_connect, this, boost::asio::placeholders::error));
::memset(getBuffer, '\0', 1024);
}
Client::~Client()
{
}
void Client::handle_connect(const boost::system::error_code& error)
{
if (!error)
{
// 一連上,就向服務(wù)端發(fā)送信息
boost::asio::async_write(socket_, boost::asio::buffer("hello,server!"),
boost::bind(&Client::handle_write, this, boost::asio::placeholders::error));
// boost::asio::async_read(...)讀取的字節(jié)長(zhǎng)度不能大于數(shù)據(jù)流的長(zhǎng)度,否則就會(huì)進(jìn)入
// ioservice.run()線(xiàn)程等待,read后面的就不執(zhí)行了。
//boost::asio::async_read(socket,
// boost::asio::buffer(getBuffer,1024),
// boost::bind(&client::handle_read,this,boost::asio::placeholders::error)
// );
socket_.async_read_some(boost::asio::buffer(getBuffer, 1024),
boost::bind(&Client::handle_read, this, boost::asio::placeholders::error));
}
else
{
socket_.close();
}
}
void Client::handle_read(const boost::system::error_code& error)
{
if (!error)
{
std::cout << getBuffer << std::endl;
//boost::asio::async_read(socket,
// boost::asio::buffer(getBuffer,1024),
// boost::bind(&client::handle_read,this,boost::asio::placeholders::error)
// );
//這樣就可以實(shí)現(xiàn)循環(huán)讀取了,相當(dāng)于while(1)
//當(dāng)然,到了這里,做過(guò)網(wǎng)絡(luò)的朋友就應(yīng)該相當(dāng)熟悉了,一些邏輯就可以自行擴(kuò)展了
//想做聊天室的朋友可以用多線(xiàn)程來(lái)實(shí)現(xiàn)
socket_.async_read_some(boost::asio::buffer(getBuffer, 1024),
boost::bind(&Client::handle_read, this, boost::asio::placeholders::error));
}
else
{
socket_.close();
}
}
void Client::handle_write(const boost::system::error_code& error)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Client.h"
using namespace boost::asio::ip;
using namespace boost::asio;
int _tmain(int argc, _TCHAR* argv[])
{
io_service ioservice;
tcp::endpoint endpoint(address_v4::from_string("127.0.0.1"), 8100);
//ClientPtr client_ptr(new Client(io_service, endpoint));
Client client(ioservice, endpoint);
ioservice.run();
return 0;
}