C++ 管道

服务端:
// PipeServer.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <windows.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
	HANDLE hPipe = CreateNamedPipeW(L"\\\\.\\pipe\\PipeTest",
		PIPE_ACCESS_DUPLEX,
		PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
		PIPE_UNLIMITED_INSTANCES,
		4096,
		4096,
		0,
		NULL);

	//PIPE_ACCESS_DUPLEX 表示可读可写  
	if (hPipe == INVALID_HANDLE_VALUE) {
		printf("create pipe fail\n");
	}

	if (ConnectNamedPipe(hPipe, NULL) || (GetLastError() == ERROR_PIPE_CONNECTED)) {
		DWORD cbBytesRead;
		char chRequest[4096];
		bool fSuccess = ReadFile(hPipe, chRequest, 4096, &cbBytesRead, NULL);
		chRequest[cbBytesRead] = '\0';
		printf("%s\n", chRequest);
		if (!fSuccess || cbBytesRead == 0) {
			
		}
		char str[] = {"123123"};
		WriteFile(hPipe, str, strlen(str), &cbBytesRead, NULL);
		Sleep(2000);
		DisconnectNamedPipe(hPipe);
	}
	else {
		CloseHandle(hPipe);
		printf("close");
	}
	CloseHandle(hPipe);
	return 0;
}

客户端端:

// PipeClient.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <windows.h>

int _tmain(int argc, _TCHAR* argv[])
{
	HANDLE m_hPipeToMain = CreateFile(L"\\\\.\\pipe\\PipeTest",
		GENERIC_WRITE | GENERIC_READ,
		0,
		NULL,
		OPEN_EXISTING,
		0,
		NULL);

	if (m_hPipeToMain != 0 || m_hPipeToMain == INVALID_HANDLE_VALUE) {
		DWORD dwWrite;
		char szPipeUpdate[200] = "send message form client";
		WriteFile(m_hPipeToMain, szPipeUpdate, strlen(szPipeUpdate), &dwWrite, NULL);
		printf("send pipe success\n");
		ZeroMemory(szPipeUpdate, 200);
		ReadFile(m_hPipeToMain, szPipeUpdate, 200, &dwWrite, NULL);
		Sleep(2000);
		printf("%s\n", szPipeUpdate);
		CloseHandle(m_hPipeToMain);
	}
	else{
		printf("ERROR\n");
	}
	return 0;
}



版权声明:本文为博主原创文章,未经博主允许不得转载。

 

转载于:https://www.cnblogs.com/qq76211822/p/4712002.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值