【Boost】boost庫asio詳解7——boost::asio::buffer用法

來源:互聯網
上載者:User
1. asio::buffer常用的構造方法

asio::buffer有多種的構造方法,而且buffer大小是自動管理的
1.1 字元數組

char d1[128];size_t bytes_transferred = socket.receive(boost::asio::buffer(d1));
1.2 字元向量
std::vector<char> d2(128);size_t bytes_transferred = socket.receive(boost::asio::buffer(d2));
1.3 boost的數組
boost::array<char, 128> d3;size_t bytes_transferred = sock.receive(boost::asio::buffer(d3)); 
1.4 字串
string str = "hello world";bytes_transferred = socket.send(boost::asio::buffer(str)); 
2. asio::buffer的常用方法2.1 轉換方法
boost::asio::mutable_buffer b1 =boost::asio::buffer(str);unsigned char* p1 = boost::asio::buffer_cast<unsigned char*>(b1);
2.2 擷取大小
std::size_t s1 = boost::asio::buffer_size(b1);
3. asio::buffer的讀寫問題

注意的是boost::asio::const_buffer是唯讀buffer, 而boost::asio::mutable_buffer則可寫。
讀寫buffer也是有講究的
3.1 與transfer_all()結合

boost::array<char, 128> buf;boost::system::error_code ec;std::size_t n = boost::asio::read(    socket,    boost::asio::buffer(buf),    boost::asio::transfer_all(),    ec);if (ec){  // An error occurred.}else{  // n == 128}

boost::asio::transfer_all()能夠使buffer中的所有資料都傳送完畢。即讀滿buffer為止。
3.2 與transfer_at_least()結合

std::size_t n = boost::asio::read(    socket,    boost::asio::buffer(buf),    boost::asio::transfer_at_least(64),    ec);

意義即讀滿64位元組為止。返回。
當然還有最常用的bytes_transferred,這個例子就很多了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.