Daytime.2 - A synchronous TCP daytime server

Programming/Boost asio 2015. 4. 19. 13:05

다음에 기반함

http://www.boost.org/doc/libs/1_57_0/doc/html/boost_asio/tutorial/tutdaytime2.html


이번엔 TCP asio 를 사용하여 어떻게 서버 응용프로그램을 구현할 수 있는지 살펴본다.

#include <ctime>
#include <iostream>
#include <string>
#include <boost/asio.hpp>

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


클라이언트로 다시 보내줄 문자열을 생성하는 make_daytime_string() 함수를 정의해보겠다.

이 함수는 daytime 서버 응용프로그램 내에서 재사용 될 것이다.

std::string make_daytime_string()
{
  using namespace std; // For time_t, time and ctime;
  time_t now = time(0);
  return ctime(&now);
}

int main()
{
  try
  {
    boost::asio::io_service io_service;


ip::tcp::acceptor 객체는 새로운 커넥션을 listen 하기 위해 생성하였다. IPv4, TCP 포트 13 을 listen 하도록 초기화 했다. 

    tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 13));


한번에 하나의 커넥션을 다루는 iterative 서버가 될 것이다. 클라이언트의 커넥션을 표현할 socket 를 생성하고, 커넥션을 기다리도록 하자. 

 for (;;)
    {
      tcp::socket socket(io_service);
      acceptor.accept(socket);


클라이언트가 우리의 서비스에 접속했다. 현재 시간을 확인하고 클라이언트로 정보를 보낸다.

      std::string message = make_daytime_string();

      boost::system::error_code ignored_error;
      boost::asio::write(socket, boost::asio::buffer(message), ignored_error);
    }
  }


마지막으로, 예외를 처리한다. 

 catch (std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}


- full_source code



- main



- 실행결과


클라이언트바이너리를 별도로 만들어놓은 후, ( 이전 포스트 ) 서버실행후 클라이언트를 실행했다.