C++/TBC++

C++ TCP/IP 네트워킹 (TCP/IP Networking)

Caniro 2021. 3. 30. 00:09

TCP/IP 네트워킹 (TCP/IP Networking)

  • boost/asio 라이브러리를 이용하여 통신을 할 수 있다.

예제

  • 원래 서버 프로그램 하나, 클라이언트 프로그램 하나 이렇게 두 개의 파일을 만드는게 정석이지만, 한번에 보기 편하도록 프로그램 하나로 작성했다.

  • 로컬호스트의 13번 포트를 사용하는 예제이다.

    #include <iostream>
    #include <ctime>
    #include <string>
    #include <boost/asio.hpp>
    #include <thread>
    
    using boost::asio::ip::tcp;
    
    void        virtual_server()
    {
      try
      {
        boost::asio::io_service io_service;
    
        tcp::endpoint endpoint(tcp::v4(), 13);
        tcp::acceptor acceptor(io_service, endpoint);
    
        std::cout << "Server - Server started\n";
    
        while (true)
        {
          const std::string message_to_send = "Hello From Server";
    
          tcp::iostream stream;
          boost::system::error_code ec;
    
          std::cout << "Server - Waiting client...\n";
    
          acceptor.accept(*stream.rdbuf(), ec);
    
          std::cout << "Server - Accepted a client\n";
    
          if (!ec)
          {
            std::string line;
            std::getline(stream, line);
            std::cout << "Server - " << line << std::endl;
    
            stream << message_to_send;
            stream << std::endl;
          }
        }
      }
      catch (std::exception& e)
      {
        std::cerr << e.what() << std::endl;
      }
    }
    
    void        virtual_client()
    {
      try
      {
        tcp::iostream stream("127.0.0.1", std::to_string(int(13)));
    
        if (!stream)
        {
          std::cerr << "Client - Fail to connect : " << \
            stream.error().message() << std::endl;
          return ;
        }
    
        std::cout << "Client - Connected to the server\n";
    
        stream << "Hello From Client";
        stream << std::endl;
    
        std::string line;
        std::getline(stream, line);
        std::cout << "Client - " << line << std::endl;
      }
      catch (std::exception& e)
      {
        std::cerr << e.what() << std::endl;
      }
    }
    
    int            main()
    {
      auto t1 = std::thread(virtual_server);
    
      Sleep(1000);
      auto t2 = std::thread(virtual_client);
      t2.join();
    
      Sleep(1000);
      auto t3 = std::thread(virtual_client);
      t3.join();
    
      t1.join();
    }
    
    /* stdout
    Server - Server started
    Server - Waiting client...
    Client - Connected to the server
    Server - Accepted a client
    Server - Hello From Client
    Client - Hello From Server
    Server - Waiting client...
    Client - Connected to the server
    Server - Accepted a client
    Server - Hello From Client
    Client - Hello From Server
    Server - Waiting client...
    */

참고