閱讀252 返回首頁    go 阿裏雲 go 技術社區[雲棲]


進程通信係列-單向郵槽


      單向郵槽可以用於局域網的不可靠單向廣播,代碼長度一般,功能一般

       缺點:不可靠,單向

       優點:簡單,不必關心協議

單向郵槽類:

#include "stdafx.h"
#include "mailslot.h"
mailslot::mailslot(void)
{
	hmail=NULL;
}
mailslot::~mailslot(void)
{
	if(hmail)
		CloseHandle(hmail);
}
int mailslot::free()
{
	if(hmail)
	{
		CloseHandle(hmail);
		return 1;
	}
	return 0;
}

int mailslot::have()
{
	if(!hmail)return 0;
	DWORD cbMessage, cMessage;
    GetMailslotInfo(hmail,(LPDWORD) NULL, &cbMessage,&cMessage,0); 
	 if(cbMessage == MAILSLOT_NO_MESSAGE)
		 return 0;
	return 1;
}

int mailslot::create(CString name)
{
	MessageBox(0,"等待發送端","ok",MB_ICONINFORMATION);
	//創建郵槽
	hmail=CreateMailslot("\\\\.\\mailslot\\"+name,0,500,NULL);
	if(hmail==INVALID_HANDLE_VALUE||hmail==0)
	{
		MessageBox(0,"創建失敗","錯誤",MB_ICONERROR);
		hmail=0;
		return 0;
	}
	return 1;
}
CString mailslot::read()
{
	char content[200];
	DWORD dread;
	if(!ReadFile(hmail,content,200,&dread,NULL))
	{
		MessageBox(0,"讀取失敗","錯誤",MB_ICONERROR);
		return "";
	}
	return content;
}
int mailslot::connect(CString server,CString name)//server不知道填什麼可以,試了好多都不行,隻能是.或*,也許是安全問題
{
	hmail=CreateFile("\\\\"+server+"\\mailslot\\"+name,GENERIC_WRITE,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
	if(hmail==INVALID_HANDLE_VALUE||hmail==0)
	{
		MessageBox(0,"打開失敗!,請確定目標地址已準備接受","錯誤",MB_ICONERROR);
		hmail=0;
		return 0;
	}
	return 1;
}
int mailslot::send(CString content)
{
	DWORD dwrite;
	if(!WriteFile(hmail,content,content.GetLength()+1,&dwrite,NULL))
	{
		MessageBox(0,"寫入失敗","錯誤",MB_ICONERROR);
		return 0;
	}
	return 1;
}


最後更新:2017-04-03 20:43:08

  上一篇:go 雷軍VS黃章:現實主義和夢幻主義的商業對決
  下一篇:go Windows Phone自定義控件