用戶端代碼:
#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; }