};
#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)
{
// 一连上,就向服务端发送信息
boost::asio::async_write(socket_, boost::asio::buffer("hello,server!"),
boost::bind(&Client::handle_write, this, boost::asio::placeholders::error));
// boost::asio::async_read(...)读取的字节长度不能大于数据流的长度,否则就会进入
// ioservice.run()线程等待,read后面的就不执行了。
//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)
// );
//这样就可以实现循环读取了,相当于while(1)
//当然,到了这里,做过网络的朋友就应该相当熟悉了,一些逻辑就可以自行扩展了
//想做聊天室的朋友可以用多线程来实现
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;
}
posted on 2009-08-19 00:24
小王 阅读(2221)
评论(0) 编辑 收藏 引用 所属分类:
网络通讯