Windows命名管道

服务端

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

#define BUFSIZE		1024
const static char* pszPipeName = "\\\\.\\pipe\\mynamedpipe";

int _tmain(int argc, _TCHAR* argv[])
{
	BOOL bConnected = FALSE;
	BOOL bSuccess = FALSE;
	char szBufSend[BUFSIZE] = {0};
	char szBufRecv[BUFSIZE] = {0};
	DWORD dwBytesRead, dwBytesWrite;

	HANDLE hPipe = CreateNamedPipeA( 
		pszPipeName,
		PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,
		PIPE_TYPE_MESSAGE |	PIPE_READMODE_MESSAGE | PIPE_WAIT,
		PIPE_UNLIMITED_INSTANCES,
		BUFSIZE,
		BUFSIZE,
		0,
		NULL);

	if(hPipe == INVALID_HANDLE_VALUE)
	{
		printf("CreateNamedPipe failed, Error code=%d\n", GetLastError());
		return -1;
	}

	bConnected = ConnectNamedPipe(hPipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
	if(bConnected)
	{
		printf("Client connected!\n");
	}

	while(1)
	{
		bSuccess = ReadFile(hPipe, szBufRecv, sizeof(szBufRecv), &dwBytesRead, NULL);
		if(!bSuccess || dwBytesRead == 0)
		{
			if(GetLastError() == ERROR_BROKEN_PIPE)
			{
				printf("client disconnect!\n");
				break;
			}
			else
			{
				printf("ReadFile failed, Error Code=%d\n", GetLastError());
			}
		}
		printf("Read Message from client: %s\n", szBufRecv);
	}
	

	//Sleep(2000);

	strncpy_s(szBufSend, sizeof(szBufSend)-1, "Hello, Client!", sizeof(szBufSend)-1);
	bSuccess = WriteFile(hPipe, szBufSend, strlen(szBufSend), &dwBytesWrite, NULL);
	if(!bSuccess || dwBytesWrite != strlen(szBufSend))
	{
		printf("WriteFile Failed! Error Code=%d\n", GetLastError());
	}

	FlushFileBuffers(hPipe);
	DisconnectNamedPipe(hPipe);
	CloseHandle(hPipe);

	system("pause");
	return 0;
}


客户端

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

#define BUFSIZE		1024
const static char* pszPipeName = "\\\\.\\pipe\\mynamedpipe";

int _tmain(int argc, _TCHAR* argv[])
{
	HANDLE hPipe = CreateFileA(pszPipeName,
		GENERIC_READ | GENERIC_WRITE,
		0,
		NULL,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
		NULL);
	if(hPipe == INVALID_HANDLE_VALUE)
	{
		printf("Open name pipe failed\n");
		system("pause");
		return -1;
	}

	DWORD nReadBytes, nWriteByte;
	char szBuf[BUFSIZE] = {0};
	strncpy_s(szBuf, sizeof(szBuf)-1, "Hello, Server!", sizeof(szBuf)-1);
	for(int i=0; i<10; i++){
		WriteFile(hPipe, szBuf, strlen(szBuf), &nWriteByte, NULL);
		Sleep(2000);
	}
	
	//memset(szBuf, 0, sizeof(szBuf));
	//ReadFile(hPipe, szBuf, BUFSIZE, &nReadBytes, NULL);
	//printf("Recv message from server: %s\n", szBuf);

	CloseHandle(hPipe);

	system("pause");
	return 0;
}





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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值