windows NT ,windows 2000,windows95 he windows98提供了一种简单的单向"进程间通信机制" ,名字很奇怪,叫邮槽.(mailslot)..简单的说, 通过邮槽,客户端进程可将消息传送或广播给一个或多个服务器进程...在同一台机器或在跨整个网络的不同计算机的进程之间,用邮槽来开发是相当简单的事情.
由于邮槽是围绕一个广播通信体系设计出来的,所以它的可靠性不是十分的好..但是在特殊的环境中,还是相当有价值的.. 我们举个例子吧.....
比如有个文件我们每过一段时间(如5秒)要读取它的文件大小.,实现监控.,并可以把结果发给局域网内的许多用户....那么可以用邮槽来实现.....
客户端:
#include<windows.h>#include<iostream.h>int main(){ char tosend[100],buffer[100]; DWORD bufferlen=100; HANDLE hsms_slot; BOOL status; DWORD numbytewritten; hsms_slot=CreateFile("*//mailslot//sms",GENERIC_WRITE,FILE_SHARE_READ,(LPSECURITY_ATTRIBUTES)NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,(HANDLE)NULL);
if(hsms_slot==INVALID_HANDLE_VALUE) { cerr<<"ERROR: unablieto creat mailslot"<<endl; return 1; } strcpy(tosend,"test string from 127.0.0.1"); while(1) { cout<<"sending ...."<<endl; status=WriteFile(hsms_slot,tosend,(DWORD)strlen(tosend)+1,&numbytewritten,(LPOVERLAPPED)NULL); if(!status) { cerr<<"ERROR: unable to get status:"<<GetLastError()<<endl; CloseHandle(hsms_slot); return 1; } Sleep(4800); }}]
服务端:
#include<windows.h>#include<iostream.h>
int main(){ char todisplay[80]; HANDLE hsms_slot; DWORD nextsize; DWORD msgs; DWORD numbyteread; BOOL status; hsms_slot=CreateMailslot(".//mailslot//sms",0,0,(LPSECURITY_ATTRIBUTES)NULL); if(hsms_slot==INVALID_HANDLE_VALUE) { cerr<<"ERROR: unablieto creat mailslot"<<endl; return 1; } while(1) { status=GetMailslotInfo(hsms_slot,(LPDWORD)NULL,&nextsize,&msgs,(LPDWORD)NULL); if(!status) { cerr<<"ERROR: unable to get status:"<<GetLastError()<<endl; CloseHandle(hsms_slot); return 1; } if(msgs) { if(!ReadFile(hsms_slot,todisplay,nextsize,&numbyteread,(LPOVERLAPPED)NULL)) { cerr<<"ERROR: read from mailsolt"<<endl; CloseHandle(hsms_slot); return 1; } cout<<todisplay<<endl; } else Sleep(500); }}
其中//*/mailslot/sms为邮槽名 .*表示局域网的所有用户, mailslot为统一的名字....