標籤:boost c++ asio
<pre name="code" class="cpp">///////////////////////////////////////// Asio同步socket串連樣本//#include <iostream>#include <boost/thread.hpp>#include <boost/asio/io_service.hpp>#include <boost/asio.hpp>using namespace boost;typedef boost::asio::io_service IoService;typedef boost::asio::ip::tcp TCP;bool flag=true;void client() { int i=0; while(i++<10) { this_thread::sleep(posix_time::seconds(1)); //延時函數 try { IoService ios; TCP::socket so(ios); TCP::endpoint ep(asio::ip::address::from_string("127.0.0.1"),9999); //綁定對方的ip和連接埠 so.connect(ep); char str[100]={0}; so.read_some(asio::buffer(str)); //接收伺服器端送回的訊息 std::cout<<"client: read from ser:"<<str<<std::endl; } catch(std::exception&e) { std::cout<<e.what()<<std::endl; } } flag=false;}int main(){try{ IoService ios; TCP::acceptor my_acceptor(ios,TCP::endpoint(TCP::v4(),9999)); //伺服器段綁定協議和連接埠 std::cout<<my_acceptor.local_endpoint().address()<<std::endl; thread tc(&client); //開一個線程執行用戶端 while(flag) //伺服器端迴圈接收用戶端socket { std::cout<<"waiting for client..."<<std::endl; TCP::socket mysocket(ios); my_acceptor.accept(mysocket); mysocket.write_some(asio::buffer("hahahahah")); //向用戶端寫資料 } tc.join();}catch(std::exception&e){ std::cout<<e.what()<<std::endl;} return 0;}