命名管道通信的实现,转。

      最近在查Windows命名管道的时候,在CodeProject中发现了一个最小的通信的例子。转于此。客户端

#include <windows.h> 

#include <stdio.h>

#define BUFSIZE 1024

#define PIPE_TIMEOUT 5000



int main()

{



	HANDLE hFile;

	BOOL flg;

	DWORD dwWrite;

	char szPipeUpdate[200];

	hFile = CreateFileA(".//pipe//SamplePipe", GENERIC_WRITE,

		0, NULL, OPEN_EXISTING,

		0, NULL);

	

	strcpy(szPipeUpdate,"Data from Named Pipe client for createnamedpipe");

	if(hFile == INVALID_HANDLE_VALUE)

	{ 

		printf("CreateFile failed for Named Pipe client/n" );

	}

	else

	{

		flg = WriteFile(hFile, szPipeUpdate, strlen(szPipeUpdate), &dwWrite, NULL);

		if (FALSE == flg)

		{

			printf("WriteFile failed for Named Pipe client/n");

		}

		else

		{

			printf("WriteFile succeeded for Named Pipe client/n");

		}

		CloseHandle(hFile);

	}



}
服务端
#include <windows.h> 

#include <stdio.h>

#define BUFSIZE 1024

#define PIPE_TIMEOUT 5000



int main()

{



	BOOL fConnected; 

	LPTSTR lpszPipename = ".//pipe//SamplePipe"; 

	CHAR chRequest[BUFSIZE]; 

	DWORD cbBytesRead; 

	BOOL fSuccess; 

	HANDLE hPipe; 





	hPipe = CreateNamedPipe ( lpszPipename, 

		PIPE_ACCESS_DUPLEX, // read/write access 

		PIPE_TYPE_MESSAGE | // message type pipe 

		PIPE_READMODE_MESSAGE | // message-read mode 

		PIPE_WAIT, // blocking mode 

		PIPE_UNLIMITED_INSTANCES, // max. instances 

		BUFSIZE, // output buffer size 

		BUFSIZE, // input buffer size 

		PIPE_TIMEOUT, // client time-out 

		NULL); // no security attribute 



	if (hPipe == INVALID_HANDLE_VALUE) 

		return true;



	for (;;) 

	{ 

		// Trying connectnamedpipe in sample for CreateNamedPipe

		// Wait for the client to connect; if it succeeds, 

		// the function returns a nonzero value. If the function returns 

		// zero, GetLastError returns ERROR_PIPE_CONNECTED. 



		fConnected = ConnectNamedPipe(hPipe, NULL) ? 

TRUE : (GetLastError() == ERROR_PIPE_CONNECTED); 



		if (fConnected) 

		{ 

			fSuccess = ReadFile (hPipe, // handle to pipe 

				chRequest, // buffer to receive data 

				BUFSIZE, // size of buffer 

				&cbBytesRead, // number of bytes read 

				NULL); // not overlapped I/O 



			chRequest[cbBytesRead] = '/0';

			printf("Data Received: %s/n",chRequest);



			if (! fSuccess || cbBytesRead == 0) 

				break; 



			FlushFileBuffers(hPipe); 

			DisconnectNamedPipe(hPipe); 

		}

		else 

			// The client could not connect in the CreateNamedPipe sample, so close the pipe. 

			CloseHandle(hPipe); 

	} 

	CloseHandle(hPipe); 

	return 1; 



}



//End of sample using CreateNamedPipe

 

以上为同步通信的实现,若要实现异步通信,则把管道改成是PIPE_NOWAIT即可。对其稍加封装,则可以更方便地使用。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值