邮槽的应用

邮槽 在网络上进程通信为单向方式

::OnMailslotRecv() //接收端即为服务器端
{
   HANDLE hMailslot;
   CString mailhostName("");
   mailhostName= "\\\\.\\mailslot\\MyRecvMailslot";
   hMailslot = CreateMailslot(mailhostName,0,
    MAILSLOT_WAIT_FOREVER,NULL);
   if(INVALID_HANDLE_VALUE == hMailslot)
   {
      AfxMessageBox("连接失败!");
      return "0";
   }
   char buf[100];
   DWORD dwRead;
   if(!ReadFile(hMailslot,buf,100,&dwRead,NULL))
   {
      AfxMessageBox("操作失败!");
      CloseHandle(hMailslot);
      return "0";
   }
   CloseHandle(hMailslot);
   return buf;
}

在客户端要知道服务器端的主机名进行通信

::OnMailslotSend(CString strMailslot,CString hostName) //strMailslot为要发送的数据 //hostName为服务器端的主机名
{
   HANDLE hMailslot;
   CString mailhostName("");
   mailhostName.Format("\\\\%s\\mailslot\\MyRecvMailslot",hostName);
   hMailslot = CreateFile(mailhostName,GENERIC_WRITE,
    FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
   if(INVALID_HANDLE_VALUE == hMailslot)
   {
      AfxMessageBox("连接失败!");
      return;
   }

   char * buf = NULL;
   buf = new char[strMailslot.GetLength()+1];
   strcpy(buf,strMailslot);
   DWORD dwWrite;
   if(!WriteFile(hMailslot,buf,strlen(buf)+1,&dwWrite,NULL))
   {
      AfxMessageBox("操作失败!");
      CloseHandle(hMailslot);
      return;
   }
   CloseHandle(hMailslot);
}

原文地址:https://www.cnblogs.com/pbreak/p/1752301.html