zoukankan      html  css  js  c++  java
  • 命名管道的应用

    管道可以实现本地和网络上两个进程的通信

    服务器端:

    ::OnPipeCreate()  //创建命名管道

    {
       hPipe = CreateNamedPipe("\\\\.\\pipe\\MyPipe",PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,
          0,1,1024,1024,0,NULL);
       if(INVALID_HANDLE_VALUE == hPipe) //hPipe为一个全局句柄
       {
          AfxMessageBox("操作失败!");
          hPipe = NULL;
          return;
      }
       HANDLE hEvent;
       hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
       if(!hEvent)
       {
          AfxMessageBox("创建事件对象失败!");
          CloseHandle(hPipe);
          hPipe = NULL;
          return;
       }
       OVERLAPPED ovlap;
       ZeroMemory(&ovlap,sizeof(OVERLAPPED));
       ovlap.hEvent = hEvent;
       if(!ConnectNamedPipe(hPipe,&ovlap))
       {
          if(ERROR_IO_PENDING != GetLastError())
          {
             AfxMessageBox("等待客户端连接失败!");
             CloseHandle(hPipe);
             CloseHandle(hEvent);
             hPipe = NULL;
             return;
          }
       }

       if(WAIT_FAILED == WaitForSingleObject(hEvent,INFINITE))
       {
          AfxMessageBox("等待对象失败!");
          CloseHandle(hPipe);
          CloseHandle(hEvent);
          hPipe = NULL;
          return;
       }
       CloseHandle(hEvent);

    }

    ::OnPipeRead() //读管道数据
    {
       char buf[100];
       DWORD dwRead;
       if(!ReadFile(hPipe,buf,100,&dwRead,NULL))
       {
          AfxMessageBox("操作失败!");
          return;
       }
    }

    ::OnPipeWrite() //写管道数据
    {
       char buf[] = "";
       DWORD dwWrite;
       if(!WriteFile(hPipe,buf,strlen(buf)+1,&dwWrite,NULL))
       {
          AfxMessageBox("操作失败!");
          return;
       }
    }

    客户端:

    ::OnPipeConnect(CString hostName)//连接管道 ,hostName为主机名
    {

      CString pipeName("");

          pipeName.Format("\\\\%s\\pipe\\MyPipe",hostName);
       if(!WaitNamedPipe(pipeName,NMPWAIT_WAIT_FOREVER))
       {
          AfxMessageBox("连接失败!");
          return;
       }
       hPipe = CreateFile(pipeName,GENERIC_READ | GENERIC_WRITE,
        0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
       if(INVALID_HANDLE_VALUE == hPipe)
       {
          AfxMessageBox("操作失败!");
         hPipe = NULL;
        return;
       }
    }

    读取和写入管道程序 和服务器端一样

  • 相关阅读:
    WebRTC视频采集中的约束有哪些和具体的使用方法
    解决WebRTC中不同的浏览器之间适配的问题
    WebRTC如何获取音频视频设备
    用C#调用外部DLL
    null值与非null只比较大小时,只会返回false
    jsonp实现js跨域请求
    同一域名的ASP.NET网站实现Session共享
    machinekey相关信息
    从bbs.3dmgame.com与qq的登录解析oauth2.0协议
    asp.net使用wsdl文件调用接口,以及调用SSL接口报错“根据验证过程 远程证书无效”的处理
  • 原文地址:https://www.cnblogs.com/pbreak/p/1752309.html
Copyright © 2011-2022 走看看