命名管道是通過網絡來完成進程間的通信,它屏蔽了底層的網絡協議細節。
將命名管道作為一種網絡編程方案時,它實際上建立了一個C/S通信體系,並在其中可靠的傳輸數據。命名管道服務器和客戶機的區別在於:服務器是唯一一個有權創建命名管道的進程,也只有它能接受管道客戶機的連接請求。而客戶機只能同一個現成的命名管道服務器建立連接。命名管道提供了兩種基本通信模式,字節模式和消息模式。在字節模式中,數據以一個連續的字節流的形式在客戶機和服務器之間流動。而在消息模式中,客戶機和服務器則通過一系列不連續的數據單位進行數據的收發,每次在管道上發出一條消息后,它必須作為一條完整的消息讀入。
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
int _tmain(int argc, _TCHAR* argv[])
{
//接受所有安全描述(也就是把管道的連接權限降到最低).
SECURITY_ATTRIBUTES sa;
SECURITY_DESCRIPTOR sd;
if( InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION) )
{
// add a NULL disc. ACL to the security descriptor.
if (SetSecurityDescriptorDacl(&sd, TRUE, (PACL) NULL, FALSE))
{
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor =&sd;
sa.bInheritHandle = TRUE;
//創建一個命名管道,在windows中\代表zhuan'yi兩個\\代表一個\
HANDLE hNamedPipe = CreateNamedPipeA("\\\\.\\pipe\\testName",
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
PIPE_TYPE_BYTE, 1, 1024, 1024,0 , &sa);
//檢查是否創建成功
if (hNamedPipe == INVALID_HANDLE_VALUE)
{
printf("create named pipe failed!\n");
}
else Window
{
printf("create named pipe success!\n");
}
//異步IO結構
OVERLAPPED op;
ZeroMemory(&op, sizeof(OVERLAPPED));
//創建一個事件內核對象
op.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
//等待一個客戶端進行連接
BOOL b = ConnectNamedPipe(hNamedPipe, &op);
//當有客戶端進行連接時,事件變成有信號的狀態
if (WaitForSingleObject(op.hEvent, INFINITE) == 0)
{
printf("client connect success!\n");
}
else
{
printf("client connect failed!\n");
}
//連接成功后,進行通信,讀寫
char buff[100];
sprintf_s(buff, 100, "test message from server!");
DWORD cbWrite;
WriteFile(hNamedPipe, buff, strlen(buff), &cbWrite, NULL);
ZeroMemory(buff, 100);
ReadFile(hNamedPipe, buff, 100, &cbWrite, NULL);
//通信完之后,斷開連接
DisconnectNamedPipe(hNamedPipe);
//關閉管道
CloseHandle(hNamedPipe);
}
}
system("pause");
return 0;
}
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
int _tmain(int argc, _TCHAR* argv[])
{
//檢查命名管道是否存在
BOOL b = WaitNamedPipeA("\\\\.\\pipe\\testName", NMPWAIT_WAIT_FOREVER);
//打開管道
HANDLE hFile = CreateFileA("\\\\.\\pipe\\testName",
GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
//檢查是否連接成功
if (!b || hFile == INVALID_HANDLE_VALUE)
{
printf("connect failed!\n");
}
else
{
printf("connect success!\n");
}
//進行通信
char buf[100];
ZeroMemory(buf, 100);
DWORD dwRead;
ReadFile(hFile, buf, 100, &dwRead, NULL);
printf(buf);
WriteFile(hFile, "test message for client!", strlen("test message for client!"), &dwRead, NULL);
//關閉管道
CloseHandle(hFile);
system("pause");
return 0;
}
