boost之网络通信

ip::tcp的内部类型socket,acceptor以及resolver是TCP通信中最核心的类。

1.同步客户端代码:

#include <iostream>

#include <boost/asio.hpp>

#include <boost/asio/ip/address.hpp>

using namespace std;

using namespace boost::asio;



using namespace boost;



int main()

{

	io_service ios;

	cout << "client start." <<endl;

	ip::tcp::socket sock(ios);

	ip::tcp::endpoint ep(ip::address::from_string("192.168.1.100"),6688);

	sock.connect(ep);

	vector<char> str(100,0);

	sock.read_some(buffer(str));

	cout << "recive from" << sock.remote_endpoint().address();

	cout << &str[0] <<endl;

	while(1);

	return 0;

}

 同步服务器端代码:

#include <iostream>

#include <boost/asio.hpp>

#include <boost/asio/ip/address.hpp>

using namespace std;

using namespace boost::asio;



using namespace boost;



int main()

{

	io_service ios;

	cout << "server start." <<endl;

	//boost::asio::ip::tcp::acceptor acceptor(ios,boost::asio::ip:tcp::endpoint(boost::asio::ip::tcp::v4(),6688));

	//

	ip::tcp::acceptor acc(ios,ip::tcp::endpoint(ip::tcp::v4(),6688));

	cout << acc.local_endpoint().address() <<endl;

	while (true)

	{

		ip::tcp::socket sock(ios);

		acc.accept(sock);

		cout << sock.remote_endpoint().address() <<endl;

		sock.write_some(buffer("hello asio"));

	}

	return 0;

}

 2.异步服务器端代码,两个异步过程一个是接受连接异步处理->另外一个是写对象处理

#include <iostream>

#include <boost/asio.hpp>

#include <boost/asio/ip/address.hpp>

#include <boost/bind.hpp>

using namespace std;

using namespace boost::asio;



using namespace boost;



class server

{

private:

	io_service& ios;//引用不能拷贝

	ip::tcp::acceptor acceptor;

	typedef shared_ptr<ip::tcp::socket> sock_pt;

public:

	server(io_service& io):ios(io),

		acceptor(ios,ip::tcp::endpoint(ip::tcp::v4(),6688))

	{

		start();

	}

	void start()

	{

		sock_pt sock(new ip::tcp::socket(ios));

		acceptor.async_accept(*sock,bind(&server::accept_handler,this,sock));

	}

	void accept_handler(sock_pt sock)

	{

		cout << "client:";

		cout << sock->remote_endpoint().address() <<endl;

		sock->async_write_some(buffer("hello asio"),bind(&server::write_handler,this));

	}

	void write_handler()

	{

		cout << "send msg complete." <<endl;

	}

};





int main()

{

	io_service ios;

	cout << "server start." <<endl;

	server serv(ios);

	ios.run();



	return 0;

}

 

你可能感兴趣的:(boost)