服务端代码:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
HANDLE hPipe = INVALID_HANDLE_VALUE;
const char* lpszPipename = ("\\\\.\\pipe\\namedpipe_td");
do
{
hPipe = CreateNamedPipeA(lpszPipename, PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, 1024, 1024, 0, NULL);
if (hPipe == INVALID_HANDLE_VALUE)
{
cout << "Create Named pipe failed, error: " << hex << GetLastError() << endl;
break;
}
cout << "Create Named pipe:" << lpszPipename << "Successfully!" << endl;
cout << "Wating for Client Connecting..." << endl;
ConnectNamedPipe(hPipe, NULL);
cout << "Client connected, Reading msg..." << endl;
//
while (1)
{
char szBuffer[1024] = { 0 };
DWORD dwReadSize = 0;
if (!ReadFile(hPipe, szBuffer, 1024, &dwReadSize, NULL))
{
DWORD dwLastError = GetLastError();
if(dwLastError == ERROR_BROKEN_PIPE)
cout << "Client Disconnected!" << endl;
else
cout << "ReadFile Error:0x" << hex << dwLastError << endl;
break;
}
cout << "Recv:" << szBuffer << endl;
}
} while (0);
if (hPipe)
{
CloseHandle(hPipe);
}
system("pause");
}
客户端代码:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
HANDLE hPipe = INVALID_HANDLE_VALUE;
const char* lpszPipename = ("\\\\.\\pipe\\namedpipe_td");
// Connecting Pipe Server
do
{
hPipe = CreateFileA(lpszPipename, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hPipe != INVALID_HANDLE_VALUE)
{
break;
}
DWORD dwLastError = GetLastError();
if (dwLastError != ERROR_PIPE_BUSY)
{
cout << "Could not open pipe, error: " << hex << dwLastError << endl;
return -1;
}
if (!WaitNamedPipeA(lpszPipename, 20000))
{
cout << "Could not open pipe: 20 seconds wait timeout." << endl;
return -1;
}
} while (1);
// Connected , change to message-read mode.
DWORD dwMode = PIPE_READMODE_MESSAGE;
if (!SetNamedPipeHandleState(hPipe, &dwMode, NULL, NULL))
{
cout << "SetNamedPipeHandleState failed error:" << GetLastError() << endl;
return -1;
}
cout << "Sending message to Pipe Server." << endl;
DWORD cbWritten = 0;
char lpvMessage[1024] = "test";
if (!WriteFile(hPipe, lpvMessage, 1024, &cbWritten, NULL))
{
cout << "WriteFile to pipe failed. error:" << GetLastError() << endl;
return -1;
}
system("pause");
if (hPipe)
{
CloseHandle(hPipe);
}
}