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

2021. 3. 30. 00:09·SW개발/C++
반응형

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
반응형
저작자표시 (새창열림)

'SW개발 > C++' 카테고리의 다른 글

C++ 외부 라이브러리 사용, 프로젝트 템플릿  (0) 2021.03.30
C++ vcpkg  (0) 2021.03.30
C++ 비주얼 스튜디오 프로파일링 (Visual Studio Profiling)  (0) 2021.03.30
따라하며 배우는 C++ 20장  (0) 2021.03.30
C++ forward  (0) 2021.03.30
'SW개발/C++' 카테고리의 다른 글
  • C++ 외부 라이브러리 사용, 프로젝트 템플릿
  • C++ vcpkg
  • C++ 비주얼 스튜디오 프로파일링 (Visual Studio Profiling)
  • 따라하며 배우는 C++ 20장
Caniro
Caniro
  • Caniro
    Minimalism
    Caniro
  • 전체
    오늘
    어제
    • 전체보기 (319)
      • SW개발 (268)
        • Java Spring (6)
        • C++ (186)
        • Python (21)
        • Linux (16)
        • 알고리즘 (13)
        • Git (4)
        • Embedded (1)
        • Raspberrypi (9)
        • React (3)
        • Web (2)
        • Windows Device Driver (6)
      • IT(개발아님) (46)
        • Windows (26)
        • MacOS (7)
        • Utility (11)
      • 챗봇 짬통 (0)
      • 일상 (2)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

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

티스토리툴바