服务端
#include "stdafx.h"
#include <windows.h>
#define BUFSIZE 1024
const static char* pszPipeName = "\\\\.\\pipe\\mynamedpipe";
int _tmain(int argc, _TCHAR* argv[])
{
BOOL bConnected = FALSE;
BOOL bSuccess = FALSE;
char szBufSend[BUFSIZE] = {0};
char szBufRecv[BUFSIZE] = {0};
DWORD dwBytesRead, dwBytesWrite;
HANDLE hPipe = CreateNamedPipeA(
pszPipeName,
PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
BUFSIZE,
BUFSIZE,
0,
NULL);
if(hPipe == INVALID_HANDLE_VALUE)
{
printf("CreateNamedPipe failed, Error code=%d\n", GetLastError());
return -1;
}
bConnected = ConnectNamedPipe(hPipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
if(bConnected)
{
printf("Client connected!\n");
}
while(1)
{
bSuccess = ReadFile(hPipe, szBufRecv, sizeof(szBufRecv), &dwBytesRead, NULL);
if(!bSuccess || dwBytesRead == 0)
{
if(GetLastError() == ERROR_BROKEN_PIPE)
{
printf("client disconnect!\n");
break;
}
else
{
printf("ReadFile failed, Error Code=%d\n", GetLastError());
}
}
printf("Read Message from client: %s\n", szBufRecv);
}
//Sleep(2000);
strncpy_s(szBufSend, sizeof(szBufSend)-1, "Hello, Client!", sizeof(szBufSend)-1);
bSuccess = WriteFile(hPipe, szBufSend, strlen(szBufSend), &dwBytesWrite, NULL);
if(!bSuccess || dwBytesWrite != strlen(szBufSend))
{
printf("WriteFile Failed! Error Code=%d\n", GetLastError());
}
FlushFileBuffers(hPipe);
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
system("pause");
return 0;
}
#include "stdafx.h"
#include <windows.h>
#define BUFSIZE 1024
const static char* pszPipeName = "\\\\.\\pipe\\mynamedpipe";
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hPipe = CreateFileA(pszPipeName,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
NULL);
if(hPipe == INVALID_HANDLE_VALUE)
{
printf("Open name pipe failed\n");
system("pause");
return -1;
}
DWORD nReadBytes, nWriteByte;
char szBuf[BUFSIZE] = {0};
strncpy_s(szBuf, sizeof(szBuf)-1, "Hello, Server!", sizeof(szBuf)-1);
for(int i=0; i<10; i++){
WriteFile(hPipe, szBuf, strlen(szBuf), &nWriteByte, NULL);
Sleep(2000);
}
//memset(szBuf, 0, sizeof(szBuf));
//ReadFile(hPipe, szBuf, BUFSIZE, &nReadBytes, NULL);
//printf("Recv message from server: %s\n", szBuf);
CloseHandle(hPipe);
system("pause");
return 0;
}