命名管道客户端及服务器端简单代码示例

服务器端代码

//服务器端源码


#include <iostream>   
#include <Windows.h>   
using namespace std;   

int main(void)   
{   
	TCHAR strPipeName[] = L".//pipe//feng";   
/*	PSECURITY_DESCRIPTOR psd;   
	psd = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);   
	if (!InitializeSecurityDescriptor(psd, SECURITY_DESCRIPTOR_REVISION))   
	{   
		LocalFree((HLOCAL)psd);   
		return -1;   
	}   
	if (!SetSecurityDescriptorDacl(psd, TRUE, (PACL)NULL, FALSE))   
	{   
		LocalFree((HLOCAL)psd);   
		return -1;   
	}   
	SECURITY_ATTRIBUTES saAttr;   
	saAttr.nLength =sizeof(SECURITY_ATTRIBUTES);   
	saAttr.lpSecurityDescriptor = psd;   
	saAttr.bInheritHandle = TRUE;  
	HANDLE hIPC = CreateNamedPipe(strPipeName,    
		PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,    
		PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,    
		1, 0, 0, 1000, &saAttr); */  
	    HANDLE hIPC = CreateNamedPipe(strPipeName,    
		PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,    
		0,    
		1, 1024, 1024, 1000, NULL);

	if (hIPC == INVALID_HANDLE_VALUE)   
	{   
		return -1;   
	}   
	char szBuf[1024] = {0};   
	DWORD dwRead, dwWrite;   
	char szWrite[] = "Get You/n";   
	ConnectNamedPipe(hIPC, NULL);   
	while(1)   
	{   
		if (!ReadFile(hIPC, szBuf, sizeof(szBuf), &dwRead, 0))   
		{   
			//break;   
		}   
		printf("%s/n", szBuf);   
		memset(szBuf, 0, sizeof(szBuf));   

		if (!WriteFile(hIPC, szWrite, strlen(szWrite), &dwWrite, NULL))   
		{   
			//break;   
		}          
	}   
	return 0;   
};  

客户端代码
//客服端
#include <windows.h>   
#include <iostream>   
	using namespace std;   
const TCHAR szPipeName[] = L".//pipe//feng";   
int main(void)   
{   
	HANDLE hPipe = CreateFile(szPipeName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);   
	if (hPipe == INVALID_HANDLE_VALUE)   
	{   
		printf("CreateFile return [%d]!/n", GetLastError());   
		return -1;   
	}   
	DWORD dwRead, dwWrite;   
	char szBuf[1024] = {0};   

	for (int i = 0; i < 10; ++i)   
	{   
		sprintf(szBuf, "%d", i);   
		WriteFile(hPipe, szBuf, strlen(szBuf), &dwWrite, 0);   
		printf("Send %s/n", szBuf);   
		memset(szBuf, 0, sizeof(szBuf));   
		ReadFile(hPipe, szBuf, sizeof(szBuf), &dwRead, 0);   
		printf("Recv %s/n", szBuf);   
	}   
}  



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值