基于Boost的同步TCP通信

时间:2025-04-17 19:34:43

1:客户端

  

 #include <iostream>
#include <boost/asio.hpp> using namespace boost;
using namespace std;
using boost::asio::ip::tcp; int main()
{
try
{
typedef tcp::endpoint endpoint_type;
typedef tcp::socket socket_type;
typedef asio::ip::address address_type; cout<<"client start."<<endl;
asio::io_service io; socket_type sock(io);
endpoint_type ep(address_type::from_string("127.0.0.1"),); sock.connect(ep);
cout<<sock.available()<<endl; vector<char> str(sock.available()+,);
sock.receive(asio::buffer(str)); cout<<"receive from"<<sock.remote_endpoint().address();
cout<<&str[]<<endl; }
catch(std::exception& e)
{
cout<<e.what()<<endl;
}
return ;
}

2:服务端

  

 #include <iostream>
#include <boost/asio.hpp> using namespace boost;
using namespace std;
using boost::asio::ip::tcp; int main()
{
try
{
typedef tcp::acceptor acceptor_type;
typedef tcp::endpoint endpoint_type;
typedef tcp::socket socket_type; cout<<"server start."<<endl;
asio::io_service io; acceptor_type acceptor(io,endpoint_type(tcp::v4(),));
cout<<acceptor.local_endpoint().address()<<endl; for(;;)
{
socket_type sock(io);
acceptor.accept(sock); cout<<"client:";
cout<<sock.remote_endpoint().address()<<endl; sock.send(asio::buffer("hello asio"));
}
}
catch(std::exception& e)
{
cout<<e.what()<<endl;
}
return ;
}

相关文章