Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1063131
  • 博文数量: 284
  • 博客积分: 8223
  • 博客等级: 中将
  • 技术积分: 3188
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-01 13:26
文章分类

全部博文(284)

文章存档

2012年(18)

2011年(33)

2010年(83)

2009年(147)

2008年(3)

分类: C/C++

2009-10-11 10:45:38

     邮槽是win上一种简单的通讯方式,允许本机或者多主机之间无连接的通讯。由于没有固定链接,其通讯的可靠性没有保证,但是其简单性使得其应用比较广泛。邮槽通讯依靠邮槽标识来识别目标,其命名规则为
   
     其中的Mailslot不可以修改。
 
 
    简单的通讯程序如下,一服务进程监听,一客户进程向服务进程发送数据;
host.cpp
   

#include <windows.h>
#include <stdio.h>
#include <TCHAR.h>


void main(void)
{
   HANDLE Mailslot;
   char buffer[256];
   DWORD NumberOfBytesRead;

   // Create the mailslot

   if ((Mailslot = CreateMailslot(_T("\\\\.\\Mailslot\\Myslot"), 0,
        MAILSLOT_WAIT_FOREVER, NULL)) == INVALID_HANDLE_VALUE)
   {
       printf("Failed to create a mailslot %d\n", GetLastError());
       return;
    }

    // Read data from the mailslot forever!

    while (ReadFile(Mailslot, buffer, 256, &NumberOfBytesRead, NULL) != 0)
    {
       printf("%.*s\n", NumberOfBytesRead, buffer);
    }
}

 

client.cpp

#include <windows.h>
#include <stdio.h>
#include <TCHAR.h>
              
void main(int argc, char *argv[])
{
   HANDLE Mailslot;
   DWORD BytesWritten;
   CHAR ServerName[256];
                                       
  if ((Mailslot = CreateFile(_T("\\\\.\\Mailslot\\Myslot"), GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,  NULL)) == INVALID_HANDLE_VALUE)
  {
      printf("CreateFile failed with error %d\n", GetLastError());
      return;
   }
                   
   if (WriteFile(Mailslot, "I am toy", 14, &BytesWritten, NULL) == 0)
   {
      printf("WriteFile failed with error %d\n", GetLastError());
      return;
   }
   printf("Wrote %d bytes \n", BytesWritten);
   CloseHandle(Mailslot);
}

 

   注意其中字符串要用_T()进行转换,该函数使用到#include 这个头文件。一开始没有进行转换时,编译报错称字符无法转换,这与vs与以前的VC++6的字符集不同有关系,所以需要把字符进行显式转换。

阅读(718) | 评论(0) | 转发(0) |
0

上一篇:string操作

下一篇:多线程实现邮槽技术

给主人留下些什么吧!~~