// PipeServer.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <Windows.h> #include <stdio.h> //最多创建实例数 #define NUM_PIPES 1 //管道名称 #define PIPE_NAME _T("\\\\.\\Pipe\\Jim") int _tmain(int argc, _TCHAR* argv[]) { HANDLE PipeHandle = NULL; DWORD BytesRead = 0; TCHAR buffer[256] = {0}; PipeHandle = CreateNamedPipe(PIPE_NAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE|PIPE_READMODE_BYTE, NUM_PIPES, 0, 0, 1000, NULL); if (PipeHandle == INVALID_HANDLE_VALUE) { printf("CreateNamedPipe failed with error %d\n", GetLastError()); return 0; } printf("Server is now running\n"); //一直等待,直到客户端连接 if (ConnectNamedPipe(PipeHandle, NULL) == 0) { printf("ConnectNamedPipe failed with error %d\n", GetLastError()); CloseHandle(PipeHandle); return 0; } //发送消息到客户端 DWORD BytesWritten; if (WriteFile(PipeHandle, "Server Call you", 15, &BytesWritten, NULL) == 0) { printf("WriteFile failed with error %d\n", GetLastError()); CloseHandle(PipeHandle); return 0; } //等待客户端消息 if (ReadFile(PipeHandle, buffer, sizeof(buffer), &BytesRead, NULL) <= 0) { printf("ReadFile failed with error %d\n", GetLastError()); CloseHandle(PipeHandle); return 0; } printf("%.*s\n", BytesRead, buffer); if (DisconnectNamedPipe(PipeHandle) == 0) { printf("DisconnectNamedPipe failed with error %d\n", GetLastError()); return 0; } CloseHandle(PipeHandle); return 0; }
客户端源码,PipeClient.cpp。
// PipeClient.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <Windows.h> #include <stdio.h> //管道名称 #define PIPE_NAME _T("\\\\.\\Pipe\\Jim") int _tmain(int argc, _TCHAR* argv[]) { if (WaitNamedPipe(PIPE_NAME, NMPWAIT_WAIT_FOREVER) == 0) { printf("WaitNamedPipe failed with error %d\n", GetLastError()); return 0; } //Create the named pipe file handle HANDLE PipeHandle = CreateFile(PIPE_NAME, GENERIC_READ|GENERIC_WRITE, 0, (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL); if (PipeHandle == INVALID_HANDLE_VALUE) { printf("CreateFile failed with error %d\n", GetLastError()); return 0; } //接受服务端消息 DWORD BytesRead = 0; TCHAR buffer[256] = {0}; if (ReadFile(PipeHandle, buffer, sizeof(buffer), &BytesRead, NULL) <= 0) { printf("ReadFile failed with error %d\n", GetLastError()); CloseHandle(PipeHandle); return 0; } printf("%.*s\n", BytesRead, buffer); //发送消息到服务端 DWORD BytesWritten; if (WriteFile(PipeHandle, "Get it, sir!", 12, &BytesWritten, NULL) == 0) { printf("WriteFile failed with error %d\n", GetLastError()); CloseHandle(PipeHandle); return 0; } printf("Wrote %d bytes\n", BytesWritten); CloseHandle(PipeHandle); return 0; }