C++ 命名管道 IPC (四)

2014-11-24 02:37:40 · 作者: · 浏览: 14
from server to client.
//

wchar_t chResponse[] = RESPONSE_MESSAGE;
DWORD cbResponse, cbWritten;
cbResponse = sizeof(chResponse);

if (!WriteFile(
hNamedPipe, // Handle of the pipe
chResponse, // Buffer to write
cbResponse, // Number of bytes to write
&cbWritten, // Number of bytes written
NULL // Not overlapped I/O
))
{
dwError = GetLastError();
wprintf(L"WriteFile to pipe failed w/err 0x%08lx\n", dwError);
goto Cleanup;
}

wprintf(L"Send %ld bytes to client: \"%s\"\n", cbWritten, chResponse);

//
// Receive a request from client.
//

BOOL fFinishRead = FALSE;
do
{
wchar_t chRequest[BUFFER_SIZE];
DWORD cbRequest, cbRead;
cbRequest = sizeof(chRequest);

fFinishRead = ReadFile(
hNamedPipe, // Handle of the pipe
chRequest, // Buffer to receive data
cbRequest, // Size of buffer in bytes
&cbRead, // Number of bytes read
NULL // Not overlapped I/O
);

if (!fFinishRead && ERROR_MORE_DATA != GetLastError())
{
dwError = GetLastError();
wprintf(L"ReadFile from pipe failed w/err 0x%08lx\n", dwError);
goto Cleanup;
}

wprintf(L"Receive %ld bytes from client: \"%s\"\n", cbRead, chRequest);

} while (!fFinishRead); // Repeat loop if ERROR_MORE_DATA

//
// Send a response from server to client.
//

wchar_t chResponse[] = RESPONSE_MESSAGE;
DWORD cbResponse, cbWritten;
cbResponse = sizeof(chResponse);

if (!WriteFile(
hNamedPipe, // Handle of the pipe
chResponse, // Buffer to write
cbResponse, // Number of bytes to write
&cbWritten, // Number of bytes written
NULL // Not overlapped I/O
))
{
dwError = GetLastError();
wprintf(L"WriteFile to pipe failed w/err 0x%08lx\n", dwError);
goto Cleanup;
}

wprintf(L"Send %ld bytes to client: \"%s\"\n", cbWritten, chResponse);
4.调用FlushFileBuffers在断开连接之前允许客户端读取管道内容。然后断开客户端连接


[cpp] FlushFileBuffers(hNamedPipe);
DisconnectNamedPipe(hNamedPipe);

FlushFileBuffers(hNamedPipe);
DisconnectNamedPipe(hNamedPipe);
5.关闭管道


[cpp] CloseHandle(hNamedPipe);

CloseHandle(hNamedPipe);
完整代码:

CppNamedPipeServer.cpp


[cpp] #pragma region Includes
#include
#include
#include
#pragma endregion


// The full name of the pipe in the format of \\servername\pipe\pipename.
#define SERVER_NAME L"."
#define PIPE_NAME L"SamplePipe"
#define FULL_PIPE_NAME L"\\\\" SERVER_NAME L"\\pipe\\" PIPE_NAME

#define BUFFER_SIZE 1024

// Response message from client to server. '\0' is appended in the end
// because the client may be a native C++ application that expects NULL
// termiated string.
#define RESPONSE_MESSAGE L"Default response from server"


BOOL CreatePipeSecurity(PSECURITY_ATTRIBUTES *);
void FreePipeSecurity(PSECURITY_ATTRIBUTES);


int wmain(int argc, wchar_t* argv[])
{
DWORD dwError = ERROR_SUCCESS;
PSECURITY_ATTRIBUTES pSa = NULL;
HANDLE hNamedPipe = INVALID_HANDLE_VALUE;

// Prepare the security attributes (the lpSecurityAttributes parameter in
// CreateNamedPipe) for the pipe. This is optional. If the
//