65,186
社区成员




#include "stdafx.h"
#include <conio.h>
HANDLE m_hPipe;
UINT ReadProc(LPVOID lpVoid)
{
char buffer[1024]; // 数据缓存
DWORD ReadNum;
//CServerView* pView = (CServerView*)lpVoid; // 获取视句柄
if (ConnectNamedPipe(m_hPipe, NULL) == FALSE) // 等待客户机的连接
{
CloseHandle(m_hPipe); // 关闭管道句柄
//pView->m_sMessage = "与客户机建立连接失败!"; // 显示信息
//pView->Invalidate();
printf("与客户机建立连接失败!\n");
return 0;
}
else
{
//pView->m_sMessage = "与客户机建立连接!"; // 显示信息
//pView->Invalidate();
printf("与客户机建立连接!\n");
}
if (ReadFile(m_hPipe, buffer, sizeof(buffer), &ReadNum, NULL) == FALSE)// 从管道读取数据
{
CloseHandle(m_hPipe); // 关闭管道句柄
//pView->m_sMessage = "从管道读取数据失败!"; // 显示信息
//pView->Invalidate();
printf("从管道读取数据失败!\n");
}
else
{
buffer[ReadNum] = '\0'; // 显示接收到的信息
//pView->m_sMessage = CString(buffer);
//pView->Invalidate();
printf("%s\n",buffer);
}
return 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
BYTE sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = &sd;
InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(&sd, TRUE, (PACL) 0, FALSE);
m_hPipe = NULL;
m_hPipe = CreateNamedPipe(TEXT("\\\\.\\Pipe\\Test"),
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, 1024, 1024, 0, &sa);
if (m_hPipe == INVALID_HANDLE_VALUE)
{
printf("%d\n",GetLastError());
printf("创建命名管道失败!\n");
}
else
{
printf("成功创建命名管道!\n");
AfxBeginThread(ReadProc, NULL); // 开启线程
}
_getch();
return 0;
}
#include "stdafx.h"
#include <Windows.h>
#include <conio.h>
#include <atlstr.h>
int _tmain(int argc, _TCHAR* argv[])
{
CString Message = "[测试数据,由客户机发出]"; // 要发送的数据
DWORD WriteNum; // 发送的是数据长度
// 等待与服务器的连接
if (WaitNamedPipe(TEXT("\\\\.\\Pipe\\Test"), NMPWAIT_WAIT_FOREVER) == FALSE)
{
printf("等待连接失败!\n"); // 显示信息
_getch();
return -1;
}
// 打开已创建的管道句柄
HANDLE hPipe = CreateFile(TEXT("\\\\.\\Pipe\\Test"), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hPipe == INVALID_HANDLE_VALUE)
{
// 显示信息
printf("管道打开失败!\n");
_getch();
return -2;
}
else
{
printf("成功打开管道!\n"); // 显示信息
}
// 向管道写入数据
if (WriteFile(hPipe, Message, Message.GetLength(), &WriteNum, NULL) == FALSE)
{
printf("数据写入管道失败!\n"); // 显示信息
}
else
{
printf("数据成功写入管道!\n");// 显示信息
}
CloseHandle(hPipe); // 关闭管道句柄
_getch();
return 0;
}