1.问题阐述
邮槽是基于广播通信体系设计出来的,它采用无连接的不可靠的数据传输。邮槽是一种单向通信机制,创建邮槽的服务器进程读取数据,打开邮槽的客户机进程写入数据。
2.实现技巧
邮槽可以实现进程间通信,同样我们也可利用标准的Win32文件系统函数(例如:ReadFile和WriteFile)来进行数据的收发,创建邮槽的函数原型如下:
HANDLE CreateMailslot( LPCTSTR lpName, DWORD nMaxMessageSize, DWORD lReadTimeout, LPSECURITY_ATTRIBUTES lpSecurityAttributes );
|
3.实例代码
服务器端的代码参考如下:
void CMailslotSrvView::OnMailslotRecv() { // TODO: 在此添加相关代码 HANDLE hMailslot; hMailslot=CreateMailslot(".//mailslot//MyMailslot",0, MAILSLOT_WAIT_FOREVER,NULL); if(INVALID_HANDLE_VALUE==hMailslot) { MessageBox("创建邮槽失败!"); return; } char buf[100]; DWORD dwRead; if(!ReadFile(hMailslot,buf,100,&dwRead,NULL)) { MessageBox("读取数据失败!"); CloseHandle(hMailslot); return; } MessageBox(buf); CloseHandle(hMailslot); }
|
客户端的代码参考如下:
void CMailslotCltView::OnMailslotSend() { // TODO: 在此添加相关代码 HANDLE hMailslot; hMailslot=CreateFile(".//mailslot//MyMailslot",GENERIC_WRITE, FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); if(INVALID_HANDLE_VALUE==hMailslot) { MessageBox("打开邮槽失败!"); return; } char buf[]="http://www.sunxin.org"; DWORD dwWrite; if(!WriteFile(hMailslot,buf,strlen(buf)+1,&dwWrite,NULL)) { MessageBox("写入数据失败!"); CloseHandle(hMailslot); return; } CloseHandle(hMailslot); }
|
3.小结
为保证邮槽在各种Windows平台下都能够正常工作,我们传输消息的时候,应将消息的长度限制在424字节以下。