이 영역을 누르면 첫 페이지로 이동
웬디의 기묘한 이야기 블로그의 첫 페이지로 이동

웬디의 기묘한 이야기

페이지 맨 위로 올라가기

웬디의 기묘한 이야기

C/C++ Windows Hooking 개발자의 블로그 입니다! 이곳은 개발 외에도 저의 취미들이 공유되는 기묘한 이야기가 펼쳐집니다.

[C/C++] IPC - Pipe client simple example

  • 2015.12.28 00:25
  • ⌨ DEVELOPMENT/C++
반응형

PIPE Client


Server code

HOME
2015/12/21 - [Development/C/C++] - [C/C++] IPC - Pipe server simple example

이전에 소개했던 Multithreaded pipe server에 이어 client code 입니다.

모든 server - client program이 그렇듯이 client는 간단 합니다.

하는일은 서버에 접속해서 데이터를 주고 받는게 다 입니다.


바로 코드로 보겠습니다.


생성자에서 서버 정보를 입력받아 바로 접속을 시도하고, 성공 실패여부는 verify 를 통하여 확인 가능하도록 했습니다.


파이프 서버는 생성할때 서버 이름을 입력해주어야 하고, 마찬가지로 클라이언트에서 접속할때도 서버 이름을 입력해야합니다.

이름은 \\\\.\\pipe\\mynamedpipe 형태로 생성 및 접근해야합니다.



namespace pipe {
class client {

public:
    client(
        __in LPCTSTR pipe_name,
        __in_opt const DWORD pipe_wait_timeout = NMPWAIT_WAIT_FOREVER
        ) {
        do {
            if (!pipe_name) {
                break;
            }

            if (!WaitNamedPipe(
                pipe_name,
                pipe_wait_timeout)
                ) {
                break;
            }

            _pipe = CreateFile(
                pipe_name,
                (GENERIC_READ | GENERIC_WRITE),
                0,
                nullptr,
                OPEN_EXISTING,
                0,
                nullptr
                );

            if (_pipe == INVALID_HANDLE_VALUE) {
                break;
            }

        } while (false);
    }

    ~client() {
        if (_pipe != INVALID_HANDLE_VALUE) {
            CloseHandle(_pipe);
        }
    }

    bool verify() const {
        return _pipe != INVALID_HANDLE_VALUE;
    }

    bool read(
        __out size_t& bytes_read,
        __out void* read_buffer,
        __in const size_t read_buffer_size
        ) {

        bool result = false;
        DWORD real_bytes_read = 0;

        do {
            if (!ReadFile(
                _pipe,
                read_buffer,
                static_cast<DWORD>(read_buffer_size),
                &real_bytes_read,
                nullptr)
                ) {
                break;
            }

            if (real_bytes_read == 0) {
                break;
            }

            bytes_read = real_bytes_read;
            result = true;
        } while (false);

        return result;
    }

    bool write(
        __out size_t& bytes_written,
        __in void* write_data,
        __in const size_t write_data_size
        ) {

        bool result = false;
        DWORD real_bytes_written = 0;

        do {
            if (!WriteFile(
                _pipe,
                write_data,
                static_cast<DWORD>(write_data_size),
                &real_bytes_written,
                nullptr)
                ) {
                break;
            }

            if (write_data_size != real_bytes_written) {
                break;
            }

            bytes_written = real_bytes_written;
            result = true;
        } while (false);

        return result;
    }

private:
    HANDLE _pipe;

};
} // namespace pipe


이렇게 만들었으면 어떻게 사용해야할지 모르는분들을 위해 테스트 코드 입니다.

단순하게 서버와 클라이언트를 생성하여 메시지를 전달했습니다.



#include<thread>

void run_server_thread() {
    pipe::server server(L"\\\\.\\pipe\\mynamedpipe", 10);
    server.accept();

    size_t size = 0;
    wchar_t buffer[512] = {};

    server.read(size, buffer, 512);
    server.write(size, buffer, 512);
}

void run_client_thread() {
    pipe::client client(L"\\\\.\\pipe\\mynamedpipe");

    size_t size = 0;
    wchar_t buffer[512] = L"test message";
    client.write(size, buffer, 512);

    wchar_t read_buffer[512] = {};
    client.read(size, read_buffer, 512);

    OutputDebugString(buffer);
}


void Cpipe_sampleDlg::OnBnClickedButton1()
{
    std::thread run_server = std::thread(run_server_thread);
    run_server.detach();
}


void Cpipe_sampleDlg::OnBnClickedButton2()
{
    std::thread run_client = std::thread(run_client_thread);
    run_client.detach();
}


모르겠다 싶은분들은 첨부파일을 다운받아 테스트 해보시기 바랍니다. (visual studio 2015 community version 입니다.)


pipe_sample.zip


해당 클래스는 MSDN을 참조로 만들었습니다.

HOME
https://msdn.microsoft.com/ko-kr/library/windows/desktop/aa365592(v=vs.85).aspx


반응형
저작자표시 비영리 동일조건 (새창열림)

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

[C++] std::string to std::wstring 서로 변환하기  (3) 2016.01.31
[C/C++] DLL injection. 다른 Process에 내 DLL Load 하기  (5) 2016.01.03
__cdecl, __stdcall, __fastcall x86 호출 규약(Calling Convention)  (4) 2016.01.01
[C/C++] FormatMessage 윈도우 GetLastError를 메시지로!!  (0) 2015.12.29
[C/C++] IPC - Pipe server simple example  (1) 2015.12.21
[C/C++] string replace all 문자열 모두 치환  (0) 2015.12.11
[C/C++] 폴더 전체 경로 중 파일명만 가져오기  (0) 2015.12.10
관리자 권한으로 생성한 MMF User 권한으로 접근하기  (0) 2015.04.03

댓글

이 글 공유하기

  • 구독하기

    구독하기

  • 카카오톡

    카카오톡

  • 라인

    라인

  • 트위터

    트위터

  • Facebook

    Facebook

  • 카카오스토리

    카카오스토리

  • 밴드

    밴드

  • 네이버 블로그

    네이버 블로그

  • Pocket

    Pocket

  • Evernote

    Evernote

다른 글

  • __cdecl, __stdcall, __fastcall x86 호출 규약(Calling Convention)

    __cdecl, __stdcall, __fastcall x86 호출 규약(Calling Convention)

    2016.01.01
  • [C/C++] FormatMessage 윈도우 GetLastError를 메시지로!!

    [C/C++] FormatMessage 윈도우 GetLastError를 메시지로!!

    2015.12.29
  • [C/C++] IPC - Pipe server simple example

    [C/C++] IPC - Pipe server simple example

    2015.12.21
  • [C/C++] string replace all 문자열 모두 치환

    [C/C++] string replace all 문자열 모두 치환

    2015.12.11
다른 글 더 둘러보기

정보

웬디의 기묘한 이야기 블로그의 첫 페이지로 이동

웬디의 기묘한 이야기

  • 웬디의 기묘한 이야기의 첫 페이지로 이동

검색

메뉴

  • 홈
  • 태그
  • 방명록
  • 이야기

카테고리

  • 분류 전체보기 (204)
    • MY STORY (2)
    • 📸 WALKING WITH YOU (85)
      • 아이슬란드 신혼여행 이야기 (14)
      • 대한민국 구석구석 (62)
      • CONTAX N1 + T* 28-80mm (4)
      • SAMSUNG NX3000 (1)
      • 어느 멋진 날 (4)
    • ⌨ DEVELOPMENT (80)
      • BOOK:Review (1)
      • AI (13)
      • C++ (26)
      • Python (10)
      • WIndows Hooking (9)
      • Windows Kernel (3)
      • Design Pattern (3)
      • Debugging (9)
      • Tools (0)
      • Project (1)
      • Android (1)
      • 상업용 무료폰트 (4)
    • OS (4)
      • News (0)
      • Windows 일반 (4)
    • 모바일 (2)
      • 모바일 게임 (2)
    • 멘사 퍼즐 (9)
    • 생활 꿀 TIP (7)
      • 건강 (3)
      • 일상 (2)
    • 물생활 (8)
      • 골든볼 라미네지 롱핀 (8)
    • IT 기기 (2)
    • BLOG (4)
      • TISTORY BLOG TIP (3)

최근 글

인기 글

댓글

공지사항

아카이브

태그

  • 카페
  • 신혼여행
  • c
  • 해외여행
  • windbg
  • 아이슬란드
  • c++
  • AI

나의 외부 링크

  • kernel undocument api
  • 지구 관찰자의 일기
  • 지구와 지구곰

정보

WENDYS의 웬디의 기묘한 이야기

웬디의 기묘한 이야기

WENDYS

블로그 구독하기

  • 구독하기
  • RSS 피드

방문자

  • 전체 방문자
  • 오늘
  • 어제

티스토리

  • 티스토리 홈
  • 이 블로그 관리하기
  • 글쓰기
Powered by Tistory / Kakao. © WENDYS. Designed by Fraccino.

티스토리툴바