#include "stdafx.h" #include <stdio.h> #include <windows.h> #include <ctime> int main(int argc, _TCHAR* argv[]) { srand(time(NULL)); DWORD wlen = 0; Sleep(1000);//守候pipe的建立胜利! BOOL bRet = WaitNamedPipe(TEXT("\\\\.\\Pipe\\mypipe"), NMPWAIT_WAIT_FOREVER); if (!bRet) { printf("connect the namedPipe failed!\n"); return 0; } HANDLE hPipe = CreateFile( //管道属于一种特别的文件 TEXT("\\\\.\\Pipe\\mypipe"), //建立的文件名 GENERIC_READ | GENERIC_WRITE, //文件形式 0, //是不是同享 NULL, //指向一个SECURITY_ATTRIBUTES构造的指针 OPEN_EXISTING, //建立参数 FILE_ATTRIBUTE_NORMAL, //文件属性(隐蔽,只读)NORMAL为默许属性 NULL); //模板建立文件的句柄 if (INVALID_HANDLE_VALUE == hPipe) { printf("open the exit pipe failed!\n"); } else { while(true) { char buf[256] = ""; sprintf(buf,"%s%d",buf,rand()%1000); if(WriteFile(hPipe,buf,sizeof(buf),&wlen,0)==FALSE) //向效劳器发送内容 { printf("write to pipe failed!\n"); break; } else { printf("To Server: data = %s, size = %d\n", buf, wlen); char rbuf[256] = ""; DWORD rlen = 0; ReadFile(hPipe, rbuf, sizeof(rbuf), &rlen, 0); //接收效劳发送过来的内容 printf("From Server: data = %s, size = %d\n", rbuf, rlen); } Sleep(1000); } CloseHandle(hPipe);//封闭管道 } system("pause"); return 0; }
效劳端代码:
#include "stdafx.h" #include <stdio.h> #include <windows.h> #include <ctime> int main(int argc, _TCHAR* argv[]) { srand(time(NULL)); char buf[256] = ""; DWORD rlen = 0; HANDLE hPipe = CreateNamedPipe( TEXT("\\\\.\\Pipe\\mypipe"), //管道名 PIPE_ACCESS_DUPLEX, //管道范例 PIPE_TYPE_MESSAGE|PIPE_READMODE_MESSAGE|PIPE_WAIT, //管道参数 PIPE_UNLIMITED_INSTANCES, //管道能建立的最大实例数目 0, //输出缓冲区长度 0示意默许 0, //输入缓冲区长度 0示意默许 NMPWAIT_WAIT_FOREVER, //超时时候 NULL); //指定一个SECURITY_ATTRIBUTES构造,或许通报零值 if (INVALID_HANDLE_VALUE == hPipe) { printf("Create Pipe Error(%d)\n",GetLastError()); } else { printf("Waiting For Client Connection...\n"); if(!ConnectNamedPipe(hPipe, NULL)) //壅塞守候客户端衔接。 { printf("Connection failed!\n"); } else { printf("Connection Success!\n"); } while (true) { if(!ReadFile(hPipe,buf,256,&rlen,NULL)) //接收客户端发送过来的内容 { printf("Read Data From Pipe Failed!\n"); break; } else { printf("From Client: data = %s, size = %d\n", buf, rlen); char wbuf[256] = ""; sprintf(wbuf, "%s%d", wbuf, rand()%1000); DWORD wlen = 0; WriteFile(hPipe, wbuf, sizeof(wbuf), &wlen, 0); //向客户端发送内容 printf("To Client: data = %s, size = %d\n", wbuf, wlen); Sleep(1000); } } FlushFileBuffers(hPipe); DisconnectNamedPipe(hPipe); CloseHandle(hPipe);//封闭管道 } system("pause"); return 0; }
以上就是定名管道跨历程通信的细致内容,更多请关注ki4网别的相干文章!