void CChildView::OnCreateNamedPipe() { LPCTSTR szPipeName = TEXT("\\\\.\\pipe\\mypipe"); hNamedPipe = CreateNamedPipe(szPipeName,PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE, 1, 1024, 1024, 0, NULL); if (hNamedPipe == INVALID_HANDLE_VALUE) { TRACE("CreateNamedhPipe failed with %d\n", GetLastError()); MessageBox(_T("创建命名管道失败")); return; } HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (NULL == hEvent) { MessageBox(_T("创建事件失败")); CloseHandle(hNamedPipe); hNamedPipe = NULL; return; } OVERLAPPED ovlap; ZeroMemory(&ovlap, sizeof(OVERLAPPED)); ovlap.hEvent = hEvent; if (!ConnectNamedPipe(hNamedPipe, &ovlap)) { if (ERROR_IO_PENDING != GetLastError()) { MessageBox(_T("等待客户端连接失败")); CloseHandle(hNamedPipe); CloseHandle(hEvent); hNamedPipe = NULL; hEvent = NULL; return; } } if (WaitForSingleObject(hEvent,INFINITE) == WAIT_FAILED) { MessageBox(_T("等待对象失败")); CloseHandle(hNamedPipe); CloseHandle(hEvent); hNamedPipe = NULL; hEvent = NULL; return; } }
void CChildView::OnSreadNamedPipe() { char szBuf[100] = { 0 }; DWORD dwRead; if (!ReadFile(hNamedPipe, szBuf, 100, &dwRead, NULL)) { MessageBox(_T("读取数据失败")); return; } MessageBox((CStringW)szBuf); }
void CChildView::OnSwriteNamedpipe() { char szBuf[] = "OnNamedPipe Server"; DWORD dwWrite; if (!WriteFile(hNamedPipe, szBuf, strlen(szBuf) + 1, &dwWrite, NULL)) { MessageBox(_T("写入数据失败")); return; } }
|