boost asio非同步讀寫網路聊天程式用戶端 執行個體詳解

來源:互聯網
上載者:User

標籤:asio   c++   boost   非同步作業   tcp   

//// chat_client.cpp// ~~~~~~~~~~~~~~~//// Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com)//// Distributed under the Boost Software License, Version 1.0. (See accompanying// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)////boost開發文檔中即時聊天程式的用戶端//實現的大致思路是:在建立的用戶端執行個體中初始化socket、串連伺服器端,並且不斷的進行著非同步讀操作(從伺服器端讀資料)//在主線程中,從console中不斷讀取要被發送的訊息,並且把這些訊息post至io_service,然後進行非同步寫操作//讀寫socket都是用非同步作業//這種方法不同於分別開一個讀線程,一個寫線程, 它的優勢是線程不會一直等待讀寫資料,在並發數大的情況下通過非同步讀寫能提高資源使用率#include <cstdlib>#include <deque>#include <iostream>#include <boost/bind.hpp>#include <boost/asio.hpp>#include <boost/thread/thread.hpp>#include "chat_message.hpp"using boost::asio::ip::tcp;typedef std::deque<chat_message> chat_message_queue;class chat_client{public:  chat_client(boost::asio::io_service& io_service,      tcp::resolver::iterator endpoint_iterator)    : io_service_(io_service),      socket_(io_service) //使得成員函數能直接使用這些變數  {    boost::asio::async_connect(socket_, endpoint_iterator,        boost::bind(&chat_client::handle_connect, this,          boost::asio::placeholders::error)); //所有的操作都採用非同步方式  }  void write(const chat_message& msg)  {    io_service_.post(boost::bind(&chat_client::do_write, this, msg)); //將訊息主動投遞給io_service  }  void close()  {    io_service_.post(boost::bind(&chat_client::do_close, this)); //這個close函數是用戶端要主動終止時調用  do_close函數是從伺服器端                                                                //讀資料失敗時調用  }private:  void handle_connect(const boost::system::error_code& error)  {    if (!error)    {      boost::asio::async_read(socket_,          boost::asio::buffer(read_msg_.data(), chat_message::header_length), //讀取資料前序          boost::bind(&chat_client::handle_read_header, this,            boost::asio::placeholders::error));    }  }  void handle_read_header(const boost::system::error_code& error)  {    if (!error && read_msg_.decode_header()) //分別處理資料前序和資料部分    {      boost::asio::async_read(socket_,          boost::asio::buffer(read_msg_.body(), read_msg_.body_length()),//讀取資料包資料部分          boost::bind(&chat_client::handle_read_body, this,            boost::asio::placeholders::error));    }    else    {      do_close();    }  }  void handle_read_body(const boost::system::error_code& error)  {    if (!error)    {      std::cout.write(read_msg_.body(), read_msg_.body_length()); //輸出訊息      std::cout << "\n";      boost::asio::async_read(socket_,           boost::asio::buffer(read_msg_.data(), chat_message::header_length), //在這裡讀取下一個資料包頭          boost::bind(&chat_client::handle_read_header, this,              boost::asio::placeholders::error)); //完成一次讀操作(處理完一個資料包)  進行下一次讀操作    }    else    {      do_close();    }  }  void do_write(chat_message msg)  {    bool write_in_progress = !write_msgs_.empty(); //空的話變數為false    write_msgs_.push_back(msg); //把要寫的資料push至寫隊列    if (!write_in_progress)//隊列初始為空白 push一個msg後就有一個元素了    {      boost::asio::async_write(socket_,          boost::asio::buffer(write_msgs_.front().data(),            write_msgs_.front().length()),          boost::bind(&chat_client::handle_write, this,             boost::asio::placeholders::error));    }  }  void handle_write(const boost::system::error_code& error)//第一個訊息單獨處理,剩下的才更好操作  {    if (!error)    {      write_msgs_.pop_front();//剛才處理完一個資料 所以要pop一個      if (!write_msgs_.empty())        {        boost::asio::async_write(socket_,            boost::asio::buffer(write_msgs_.front().data(),              write_msgs_.front().length()),            boost::bind(&chat_client::handle_write, this,              boost::asio::placeholders::error)); //迴圈處理剩餘的訊息      }    }    else    {      do_close();    }  }  void do_close()  {    socket_.close();  }private:  boost::asio::io_service& io_service_;  tcp::socket socket_;  chat_message read_msg_;  chat_message_queue write_msgs_;};int main(int argc, char* argv[]){  try  {    if (argc != 3)    {      std::cerr << "Usage: chat_client <host> <port>\n";      return 1;    }    boost::asio::io_service io_service;    tcp::resolver resolver(io_service);    tcp::resolver::query query(argv[1], argv[2]); //輸入ip(或網域名稱)和連接埠號碼    tcp::resolver::iterator iterator = resolver.resolve(query);    chat_client c(io_service, iterator);    boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service));    char line[chat_message::max_body_length + 1];    while (std::cin.getline(line, chat_message::max_body_length + 1))    {      using namespace std; // For strlen and memcpy.      chat_message msg;      msg.body_length(strlen(line));      memcpy(msg.body(), line, msg.body_length());      msg.encode_header();      c.write(msg);    }    c.close();    t.join();  }  catch (std::exception& e)  {    std::cerr << "Exception: " << e.what() << "\n";  }  return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.