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

2021. 3. 30. 00:09·C++/TBC++

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...
    */

참고

  • https://www.boost.org/doc/libs/1_68_0/doc/html/boost_asio/overview/networking/iostreams.html
저작자표시 (새창열림)

'C++ > TBC++' 카테고리의 다른 글

C++ 외부 라이브러리 사용, 프로젝트 템플릿  (0) 2021.03.30
따라하며 배우는 C++ 20장  (0) 2021.03.30
C++ 멀티쓰레딩 예제 (벡터 내적)  (0) 2021.03.30
따라하며 배우는 C++ 19장  (0) 2021.03.30
따라하며 배우는 C++ 18장  (0) 2021.03.26
'C++/TBC++' 카테고리의 다른 글
  • C++ 외부 라이브러리 사용, 프로젝트 템플릿
  • 따라하며 배우는 C++ 20장
  • C++ 멀티쓰레딩 예제 (벡터 내적)
  • 따라하며 배우는 C++ 19장
Caniro
Caniro
  • Caniro
    Minimalism
    Caniro
  • 전체
    오늘
    어제
    • 분류 전체보기 (317)
      • Algorithm (13)
        • 알기 쉬운 알고리즘 (10)
        • Search (1)
        • Sort (2)
      • Arduino (0)
      • C++ (185)
        • Class (46)
        • Exception (6)
        • Library (51)
        • Overloading (10)
        • SmartPointer (5)
        • Syntax (33)
        • TBC++ (23)
        • Templates (9)
        • VisualStudio (2)
      • Embedded (1)
      • Git (4)
      • Java (5)
      • Linux (16)
        • Error (1)
        • Linux Structure (11)
      • MacOS (7)
      • OS (1)
        • Concurrency (1)
      • Python (21)
        • Class (1)
        • Function (2)
        • Syntax (17)
      • Raspberrypi (9)
      • Review (1)
      • Utility (12)
        • VSCode (5)
        • VirtualBox (3)
      • Web (8)
        • Nginx (1)
        • React (3)
        • Django (1)
      • Windows (20)
        • Registry (3)
        • WSL (1)
        • DeviceDriver (6)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    윈도우 명령어
    그림판
    mspaint
    시스템 복구
    스프링
    vscode
    스프링 프레임워크 핵심 기술
    Windows 11
    windows
    logi options
    백기선
    java
    SFC
    citrix workspace
    KakaoTalk
    unix
    spring
    EXCLUDE
    제외
    MacOS
    Workspace
    로지텍 마우스 제스처
    윈도우
    dism
    Solaris 10
    알림
    맥북 카카오톡 알림 안뜸
    SunOS 5.1
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Caniro
C++ TCP/IP 네트워킹 (TCP/IP Networking)
상단으로

티스토리툴바