apis.cpp

来自「用API实现简单的信息通信」· C++ 代码 · 共 77 行

CPP
77
字号
/*实现一个命名管道客户机时,要求开发一个应用程序,令其建立与某个命名管道服务器
的连接。客户机不可创建命名管道实例,但可打开来自服务器的、现成的实例。
1) 用A P I函数Wa i t N a m e d P i p e,等候一个命名管道实例可供自己使用。
2) 用A P I函数C r e a t e F i l e,建立与命名管道的连接。
3) 用A P I函数Wr i t e F i l e和R e a d F i l e,分别向服务器发送数据,或从中接收数据。
4) 用A P I函数C l o s e H a n d l e,关闭打开的命名管道会话。
建立一个连接之前,客户机需要用Wa i t N a m e d P i p e函数,检查是否存在一个现成的命名管
道实例。
Wa i t N a m e d P i p e成功完成后,客户机需要用C r e a t e F i l e这个A P I函数,打开指向服务器命名
管道实例的一个句柄。
如C r e a t e F i l e成功完成,未产生错误,客户机应用便可开始通过R e a d F i l e和Wr i t e F i l e函数,
在命名管道上发送及接收数据。应用程序完成了数据的处理之后,可用C l o s e H a n d l e函数,将连接
关闭(断开)。*/
#include <windows.h>
#include <conio.h>
#include <stdlib.h>
#include <fstream.h>

#include <winbase.h>
#include <winuser.h>
#include <io.h>

#include <string.h>
#include <stdio.h>

#define Pipe_Name "\\\\.\\pipe\\COTWO"
void main()
{
	char smsg[256];  //待发送的信息
	HANDLE clientpipe;
	DWORD send;
	int i=0;

	/*char c=getchar();
	while(c!=10)
	{
		smsg[i]=c;
		i++;
		c=getchar();
	}*/		

	if(WaitNamedPipe(Pipe_Name,NMPWAIT_WAIT_FOREVER)==0)    //检查是否存在一个现成的命名管道实例
	{
		printf("WaitNamedPipe failed with error %d\n", GetLastError());
		return;
	}

	if((clientpipe=CreateFile(Pipe_Name,
							  GENERIC_READ|GENERIC_WRITE,0,
							  (LPSECURITY_ATTRIBUTES) NULL,OPEN_EXISTING,
							  FILE_ATTRIBUTE_NORMAL,
							  (HANDLE)NULL))==INVALID_HANDLE_VALUE)    //打开指向命名管道实例的一个句柄
	{
		printf("CreateFile failed with error %d\n", GetLastError());
		return;
	}
	
	while(1){
	printf("Input a String: ");
	gets(smsg);
	if (!WriteFile(clientpipe,
				   smsg, (DWORD) strlen(smsg)+1,
				   &send, (LPOVERLAPPED) NULL))
	{
		printf("WriteFile failed with error %d\n", GetLastError());
		CloseHandle(clientpipe);
		return;
	}
	if (strcmp(smsg, "exit") == 0)
		break;
	}

	printf("Wrote %d bytes",send);

	CloseHandle(clientpipe);
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?