Garbage Collection

塵も積もれば山

目次

Blog 利用状況

ニュース

C++とかC#とか数学ネタを投下していく予定です。

[その他のページ]
日々の四方山話を綴った日記出水の日記帳

書庫

日記カテゴリ

[C++]楽々TCPサーバ

[C++]楽々UDPサーバ

ということで、今回はTCPサーバです。

#include <iostream>
#include <string>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;

class tcp_connection
  : public boost::enable_shared_from_this<tcp_connection>{
  tcp::socket socket_;
  boost::array<char, 4096> recv_buffer_;

private:
  tcp_connection(boost::asio::io_service& io_service)
    : socket_(io_service){}

  void handle_write(boost::shared_ptr<std::vector<char> > /* sendbuf */, size_t /* len */ ){}

  void handle_receive(const boost::system::error_code& error, size_t len)
  {
    if (!error || error == boost::asio::error::message_size){
      /* メッセージ表示 */
      std::string message(recv_buffer_.data(), len);
      std::cout << message << std::endl;

      /* エコー */
      boost::shared_ptr<std::vector<char> > sendbuf( 
        new std::vector<char>(recv_buffer_.begin(), recv_buffer_.begin() + len) );

      boost::asio::async_write(socket_, boost::asio::buffer(*sendbuf),
        boost::bind(&tcp_connection::handle_write, shared_from_this(), sendbuf, len));

      start_receive();
    }
  }

  void start_receive(){
    socket_.async_receive(
      boost::asio::buffer(recv_buffer_), 
      boost::bind(&tcp_connection::handle_receive, shared_from_this(),
      boost::asio::placeholders::error, _2));
  }
public:
  typedef boost::shared_ptr<tcp_connection> pointer;

  static pointer create(boost::asio::io_service& io_service){
    return pointer(new tcp_connection(io_service));
  }

  tcp::socket& socket(){
    return socket_;
  }

  void start(){
    std::cout << socket_.remote_endpoint().address() << ":" << socket_.remote_endpoint().port() << std::endl ;

    start_receive();
  }
};

class tcp_server{
  tcp::acceptor acceptor_;
  void start_accept(){
    tcp_connection::pointer new_connection =
      tcp_connection::create(acceptor_.io_service());

    acceptor_.async_accept(new_connection->socket(),
      boost::bind(&tcp_server::handle_accept, this, new_connection,
      boost::asio::placeholders::error));
  }

  void handle_accept(tcp_connection::pointer new_connection,
    const boost::system::error_code& error){
    if (!error){
      new_connection->start();
      start_accept();
    }
  }
public:
  tcp_server(boost::asio::io_service& io_service, int port)
    : acceptor_(io_service, tcp::endpoint(tcp::v4(), port)){
      start_accept();
  }
};

int main(){
  try{
    boost::asio::io_service io_service;
    tcp_server server1(io_service, 10000);
//  udp_server server2(io_service, 10000);
    io_service.run();
  }
  catch (std::exception& e){
    std::cerr << e.what() << std::endl;
  }

  return 0;
}

TCPのサーバを作った人ならわかるでしょうが、TCPには2つの段階があります。

まず、相手からの接続を受け付けるためのリスナーを作成します。
その後、誰かが接続してくればそこで接続を確立し、再度リスナーは待ち受けに戻ります。

まずはその部分から見てみましょう。

  tcp_server(boost::asio::io_service& io_service, int port)
    : acceptor_(io_service, tcp::endpoint(tcp::v4(), port)){
      start_accept();
  }

コンストラクタです。
UDPとほぼ同じと言っていいでしょう。

  void start_accept(){
    tcp_connection::pointer new_connection =
      tcp_connection::create(acceptor_.io_service());

    acceptor_.async_accept(new_connection->socket(),
      boost::bind(&tcp_server::handle_accept, this, new_connection,
      boost::asio::placeholders::error));
  }

ここで、リスナーのイベントを登録します。
リスナーの待ち受けにソケットクラスが必要なので、
この時点で接続した時のクラスを作っておきます。

  void handle_accept(tcp_connection::pointer new_connection,
    const boost::system::error_code& error){
    if (!error){
      new_connection->start();
      start_accept();
    }
  }

接続時のハンドルクラスです。
new_connectionに接続した時の処理を行ない、再度リスナーに待ち受けイベントを登録します。

次は接続したときの相手をするtcp_connectionクラスです。

コンストラクタ、createは省略します。ま、見ればわかりますね。
なお、コンストラクタがprivateにあるのはnewで他のクラスから生成できないようにするためです。
newの代わりにcreate関数を使ってね、って事ですね。

  void start(){
    std::cout << socket_.remote_endpoint().address() << ":" << socket_.remote_endpoint().port() << std::endl ;

    start_receive();
  }

接続してきたら、誰か接続してきたのかを表示して、パケットが飛んできた時の待ち受けを行ないます。
socket_.remote_endpoint()で誰が接続したのかを取り出すことが出来ます。
なお、socket_.local_endpoint()は自分自身のIPやポートが入っていますので注意。

start_receive関数も省略。ただイベント登録しているだけですね。

  void handle_receive(const boost::system::error_code& error, size_t len)
  {
    if (!error || error == boost::asio::error::message_size){
      /* メッセージ表示 */
      std::string message(recv_buffer_.data(), len);
      std::cout << message << std::endl;

      /* エコー */
      boost::shared_ptr<std::vector<char> > sendbuf( 
        new std::vector<char>(recv_buffer_.begin(), recv_buffer_.begin() + len) );

      boost::asio::async_write(socket_, boost::asio::buffer(*sendbuf),
        boost::bind(&tcp_connection::handle_write, shared_from_this(), sendbuf, len));

      start_receive();
    }
  }

UDPサーバと同じく、相手から送られたメッセージを画面に表示して、
その後送られたパケットをそのまま投げ返しています。

なお、async_writeというのを使っています。
UDPと同じく、send関数を使ってもいいのですが、非同期送信を使ってみました。
送信が終了したらhandle_write関数が呼び出されます。

send関数を使う場合は送信用バッファをローカルに確保しても良いのですが、
非同期送信なのでローカルに確保するとまずいことになります。
また、メンバー変数として確保してもやはり先にhandle_recieveが先に2回呼ばれてしまうと、
最初のバッファが2回目のデータで上書きされてしまいます。
そこで、shared_ptrを使い、毎回送信用バッファを作成しているわけです。

handle_writeは何もしていません。
特に送信後に何かを行うイベントがないのでこうなっています。
ではこの関数は要らないの?と思いますが、引数に送信バッファを持っています。
つまり、このshared_ptrがこの関数が終わるまで生きているわけです。
この関数は送信後に呼ばれるため、送信用バッファを送信後に破棄するためにこの関数が必要になります。

ということで、TCPサーバも100行程度で作れました。
いやぁ、boost便利ですね!

投稿日時 : 2010年10月26日 9:34

Feedback

# [C++]あちこちを転々と shared_ptr 2010/10/28 11:20 Garbage Collection

[C++]あちこちを転々と shared_ptr

# KTwicuRJGaQHx 2011/12/13 17:41 http://www.birthcontrolremedy.com/birth-control/ya

Hello! Read the pages not for the first day. Yes, the connection speed is not good. How can I subscribe? I would like to read you in the future!...

# KweLlCVwSfnusapVd 2011/12/22 21:53 http://www.discreetpharmacist.com/

RGADuW As I have expected, the writer blurted out..!

# oFpqCRggCYkkIV 2014/08/28 2:48 http://crorkz.com/

B6bYZH F*ckin' tremendous things here. I'm very glad to see your article. Thanks a lot and i'm looking forward to contact you. Will you please drop me a mail?

# Good web site you have got here.. It's difficult to find quality writing like yours these days. I honestly appreciate people like you! Take care!! 2019/06/01 20:57 Good web site you have got here.. It's difficult t

Good web site you have got here.. It's difficult to find quality
writing like yours these days. I honestly appreciate people like you!

Take care!!

# all the time i used to read smaller posts which as well clear their motive, and that is also happening with this paragraph which I am reading at this place. 2019/06/03 13:04 all the time i used to read smaller posts which as

all the time i used to read smaller posts which as well clear their motive,
and that is also happening with this paragraph which I am reading
at this place.

# Having read this I thought it was extremely enlightening. I appreciate you finding the time and energy to put this information together. I once again find myself personally spending a significant amount of time both reading and posting comments. But so 2019/06/05 5:56 Having read this I thought it was extremely enligh

Having read this I thought it was extremely enlightening.
I appreciate you finding the time and energy to put this information together.

I once again find myself personally spending a significant amount
of time both reading and posting comments. But so what, it was still worth it!

# It's very trouble-free to find out any matter on web as compared to books, as I found this post at this web site. 2019/06/07 10:40 It's very trouble-free to find out any matter on w

It's very trouble-free to find out any matter on web
as compared to books, as I found this post at this
web site.

# Hey there just wanted to give you a quick heads up. The text in your content seem to be running off the screen in Ie. I'm not sure if this is a format issue or something to do with internet browser compatibility but I thought I'd post to let you know. T 2019/07/31 23:36 Hey there just wanted to give you a quick heads up

Hey there just wanted to give you a quick heads up.

The text in your content seem to be running off the screen in Ie.
I'm not sure if this is a format issue or something to do with internet
browser compatibility but I thought I'd post to let you know.
The design and style look great though! Hope you get the issue
fixed soon. Kudos

# Hey there just wanted to give you a quick heads up. The text in your content seem to be running off the screen in Ie. I'm not sure if this is a format issue or something to do with internet browser compatibility but I thought I'd post to let you know. T 2019/07/31 23:37 Hey there just wanted to give you a quick heads up

Hey there just wanted to give you a quick heads up.

The text in your content seem to be running off the screen in Ie.
I'm not sure if this is a format issue or something to do with internet
browser compatibility but I thought I'd post to let you know.
The design and style look great though! Hope you get the issue
fixed soon. Kudos

# Hey there just wanted to give you a quick heads up. The text in your content seem to be running off the screen in Ie. I'm not sure if this is a format issue or something to do with internet browser compatibility but I thought I'd post to let you know. T 2019/07/31 23:38 Hey there just wanted to give you a quick heads up

Hey there just wanted to give you a quick heads up.

The text in your content seem to be running off the screen in Ie.
I'm not sure if this is a format issue or something to do with internet
browser compatibility but I thought I'd post to let you know.
The design and style look great though! Hope you get the issue
fixed soon. Kudos

# Hey there just wanted to give you a quick heads up. The text in your content seem to be running off the screen in Ie. I'm not sure if this is a format issue or something to do with internet browser compatibility but I thought I'd post to let you know. T 2019/07/31 23:39 Hey there just wanted to give you a quick heads up

Hey there just wanted to give you a quick heads up.

The text in your content seem to be running off the screen in Ie.
I'm not sure if this is a format issue or something to do with internet
browser compatibility but I thought I'd post to let you know.
The design and style look great though! Hope you get the issue
fixed soon. Kudos

# Hello! Do you know if they make any plugins to safeguard against hackers? I'm kinda paranoid about losing everything I've worked hard on. Any suggestions? 2019/08/25 1:34 Hello! Do you know if they make any plugins to saf

Hello! Do you know if they make any plugins to safeguard against hackers?
I'm kinda paranoid about losing everything I've worked hard on. Any
suggestions?

# Illikebuisse fzcaf 2021/07/04 23:01 www.pharmaceptica.com

hydroxocloroquine https://pharmaceptica.com/

# re: [C++]??TCP??? 2021/07/15 3:31 plaquenil 200 mg twice a day

chloroguine https://chloroquineorigin.com/# hydroxy chloriquine

# Let's Optimize your Marketing. There is NO link to ANY landing page in your description.There is no way to CONTACT you here??? 2021/07/31 22:46 Let's Optimize your Marketing. There is NO link to

Let's Optimize your Marketing. There is NO link to ANY landing page in your description.There
is no way to CONTACT you here???

# Let's Optimize your Marketing. There is NO link to ANY landing page in your description.There is no way to CONTACT you here??? 2021/07/31 22:47 Let's Optimize your Marketing. There is NO link to

Let's Optimize your Marketing. There is NO link to ANY landing page in your description.There
is no way to CONTACT you here???

# Let's Optimize your Marketing. There is NO link to ANY landing page in your description.There is no way to CONTACT you here??? 2021/07/31 22:47 Let's Optimize your Marketing. There is NO link to

Let's Optimize your Marketing. There is NO link to ANY landing page in your description.There
is no way to CONTACT you here???

# Let's Optimize your Marketing. There is NO link to ANY landing page in your description.There is no way to CONTACT you here??? 2021/07/31 22:48 Let's Optimize your Marketing. There is NO link to

Let's Optimize your Marketing. There is NO link to ANY landing page in your description.There
is no way to CONTACT you here???

# What a material of un-ambiguity and preserveness of valuable know-how regarding unpredicted emotions. 2021/08/11 6:36 What a material of un-ambiguity and preserveness o

What a material of un-ambiguity and preserveness of valuable know-how regarding
unpredicted emotions.

# This is a really awesome border going across to do and also comes well suggested. These legal representatives are well mindful of the brand-new become the immigration legislation dominating in the UK. 2021/11/26 6:46 This is a really awesome border going across to do

This is a really awesome border going across
to do and also comes well suggested. These legal representatives are well mindful of the brand-new become
the immigration legislation dominating in the UK.

# uocoalcxjeba 2021/11/27 16:20 dwedayukfq

hydroxychloroquine moa https://hydro-chloroquine.com/

# Madina Soffa & Cair Upholstery Opp Moammad Ali Bin Beyat Masjid -30 6b St - Al Barsha Dubai 0507857283 sofa bed cover uae" 2022/01/27 14:43 Madina Sofa & Chair Upholstery Opp Mohammad A

Madina Sofa & Chair Upholstery

Opp Mohammad Ali Bin Beyat Maejid -30 6b St - Al Barsha
Dubai
0507857283

sofa bed cover uae"

# Madina Sofa & Chair Upholstery Opp Mohammmad Ali Bin Beyat Masjid -30 6b St - Al Barsha Dubai 0507857283 sofa uphholsterers near me" 2022/01/31 13:10 Madina Sofa & Chair Upholstery Opp Mohammad A

Madina Sofa & Chir Upholstery

Opp Mohammad Ali Bin Beyat Masjid -30 6b St - Al Barsha
Dubai
0507857283

sofa upholsterers near me"

# Свежие новости 2022/02/13 11:43 Adamppc

Где Вы ищите свежие новости?
Лично я читаю и доверяю газете https://www.ukr.net/.
Это единственный источник свежих и независимых новостей.
Рекомендую и Вам

# bwzwpzwbsdsb 2022/05/23 3:38 ovysrrlm

erythromycin family https://erythromycinn.com/#

# doors2.txt;1 2023/03/14 14:56 BBdyJsKWyyxxZ

doors2.txt;1

# For instance, on January 4, 2007, the Polish Workplace of Competition and Shopper Safety fined twenty banks a complete of PLN 164 million (about $56 million) for jointly setting Mastercard's and Visa's interchange fees. 2023/04/05 20:42 For instance, on January 4, 2007, the Polish Workp

For instance, on January 4, 2007, the Polish Workplace of Competition and Shopper Safety fined twenty banks a complete of PLN 164 million (about
$56 million) for jointly setting Mastercard's and Visa's interchange fees.

# The terms "foreign born" and "immigrant" are used mutually as well as refer to those who were birthed in an additional nation and later emigrated to the United States. Mexicans are a lot less most likely to be naturalized united stat 2023/05/30 14:36 The terms "foreign born" and "immig

The terms "foreign born" and "immigrant" are used mutually as well as refer to those who were birthed in an additional nation and
later emigrated to the United States. Mexicans are a lot less most
likely to be naturalized united state Mexicans accounted for 51 percent of the 11 million unauthorized immigrants in 2018,
according to quotes from the Migration Plan Institute
(MPI). Migration goes to brand-new highs amid degrading problems in Latin America that were
worsened by the coronavirus pandemic. "Adhering to today's Federal Circuit as well as Family members Court determination on a procedural ground, it stays within Immigration Priest Hawke's discretion to take into consideration canceling Mr Djokovic's visa under his individual power of termination within area 133C( 3) of the Migration Act," the
spokesman stated, in the very first remarks from the preacher's office after the
court quashed an earlier visa termination. ICE. Any type of policeman mandated under the program has to complete a four-week Migration Authority
Delegation Program at the Federal Police Training Center (FLETC) ICE Academy (ICEA) in Charleston, South Carolina.
There is no unique safety and security guidance - or federal laws - for flying large teams of shackled migration detainees.
Personal Privacy International, Liberty, Big Brother Watch, the Web Structure and several more
have actually shared their contempt for the expense, with a number of groups suggesting that its influence on the public's basic right to privacy must be at the
forefront of the argument-- that going over the trivial matters
of the costs is taking interest away from the bigger image.

# Innovative Sales Solutions: Partner with AccsMarket.net for Success 2024/06/21 4:26 Raymondtweby

Introducing https://Accsmarket.net, your premier destination for purchasing a wide array of accounts across diverse platforms. Whether you're in need of social media profiles, gaming logins, or business accounts, we offer a seamless and secure solution. Explore our extensive selection of verified accounts and streamline your digital endeavors with ease on https://Accsmarket.net

Click : https://Accsmarket.net

タイトル
名前
Url
コメント