命名管道客户端及服务器端简单代码示例

来源:互联网 发布:数据库图书管理系统 编辑:程序博客网 时间:2024/06/05 06:39

服务器端代码

//服务器端源码#include <iostream>   #include <Windows.h>   using namespace std;   int main(void)   {   TCHAR strPipeName[] = L"////.//pipe//feng";   /*PSECURITY_DESCRIPTOR psd;   psd = (PSECURITY_DESCRIPTOR) LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);   if (!InitializeSecurityDescriptor(psd, SECURITY_DESCRIPTOR_REVISION))   {   LocalFree((HLOCAL)psd);   return -1;   }   if (!SetSecurityDescriptorDacl(psd, TRUE, (PACL)NULL, FALSE))   {   LocalFree((HLOCAL)psd);   return -1;   }   SECURITY_ATTRIBUTES saAttr;   saAttr.nLength =sizeof(SECURITY_ATTRIBUTES);   saAttr.lpSecurityDescriptor = psd;   saAttr.bInheritHandle = TRUE;  HANDLE hIPC = CreateNamedPipe(strPipeName,    PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,    PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,    1, 0, 0, 1000, &saAttr); */      HANDLE hIPC = CreateNamedPipe(strPipeName,    PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,    0,    1, 1024, 1024, 1000, NULL);if (hIPC == INVALID_HANDLE_VALUE)   {   return -1;   }   char szBuf[1024] = {0};   DWORD dwRead, dwWrite;   char szWrite[] = "Get You/n";   ConnectNamedPipe(hIPC, NULL);   while(1)   {   if (!ReadFile(hIPC, szBuf, sizeof(szBuf), &dwRead, 0))   {   //break;   }   printf("%s/n", szBuf);   memset(szBuf, 0, sizeof(szBuf));   if (!WriteFile(hIPC, szWrite, strlen(szWrite), &dwWrite, NULL))   {   //break;   }          }   return 0;   };  

客户端代码
//客服端#include <windows.h>   #include <iostream>   using namespace std;   const TCHAR szPipeName[] = L"////.//pipe//feng";   int main(void)   {   HANDLE hPipe = CreateFile(szPipeName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);   if (hPipe == INVALID_HANDLE_VALUE)   {   printf("CreateFile return [%d]!/n", GetLastError());   return -1;   }   DWORD dwRead, dwWrite;   char szBuf[1024] = {0};   for (int i = 0; i < 10; ++i)   {   sprintf(szBuf, "%d", i);   WriteFile(hPipe, szBuf, strlen(szBuf), &dwWrite, 0);   printf("Send %s/n", szBuf);   memset(szBuf, 0, sizeof(szBuf));   ReadFile(hPipe, szBuf, sizeof(szBuf), &dwRead, 0);   printf("Recv %s/n", szBuf);   }   }  


0 0
原创粉丝点击