2017-08-18 17 views
3

我從boost :: beast網站複製websocket示例並運行它Websocket會話工作正常,但我不知道如何將接收到的multi_buffer轉換爲字符串。如何將boost beast multi_buffer轉換爲字符串?

下面的代碼是websocket會話處理程序。

void 
do_session(tcp::socket &socket) { 
    try { 
     // Construct the stream by moving in the socket 
     websocket::stream <tcp::socket> ws{std::move(socket)}; 

     // Accept the websocket handshake 
     ws.accept(); 

     while (true) { 
      // This buffer will hold the incoming message 
      boost::beast::multi_buffer buffer; 

      // Read a message 
      boost::beast::error_code ec; 
      ws.read(buffer, ec); 

      if (ec == websocket::error::closed) { 
       break; 
      } 

      // Echo the message back 
      ws.text(ws.got_text()); 
      ws.write(buffer); 
     } 

     cout << "Close" << endl; 
    } 
    catch (boost::system::system_error const &se) { 
     // This indicates that the session was closed 
     if (se.code() != websocket::error::closed) 
      std::cerr << "Error: " << se.code().message() << std::endl; 
    } 
    catch (std::exception const &e) { 
     std::cerr << "Error: " << e.what() << std::endl; 
    } 
} 

有沒有辦法將緩衝區轉換爲字符串?

回答

4

您可以在buffer.data()

std::cout << "Data read: " << boost::beast::buffers(buffer.data()) << 
std::endl; 
+0

Upvoted使用buffers - 這種簡單的技術躲避我太久。我做了: 'std :: ostringstream os; (boost :: beast :: buffers(body.data()); std :: string s = os.str(); ' –