// 10.郵槽-客戶端.cpp : 定義控制臺應用程序的入口點。
//
#include "stdafx.h"
#include <windows.h>
int _tmain(int argc, _TCHAR* argv[])
{
//1.打開郵槽對象
HANDLE hFile = CreateFile(
L"\\\\DESKTOP-NJCBKNB\\mailslot\\sample", // 郵槽名稱
GENERIC_WRITE, // 讀寫屬性
FILE_SHARE_READ, // 共享屬性
NULL, // 安全屬性
OPEN_EXISTING, // 打開方式
FILE_ATTRIBUTE_NORMAL, // 標志位
NULL); // 文件模板(默認留空)
// 2. 向mailslot寫入
DWORD dwWritten;
LPSTR lpMessage = "郵槽測試消息!";
DWORD dwMegLen = strlen(lpMessage) + sizeof(CHAR);
WriteFile(hFile, lpMessage, dwMegLen, &dwWritten, NULL);
// 3. 結束
printf("已經向郵槽寫入信息!\n");
CloseHandle(hFile);
return 0;
}
==================
// 09.郵槽-服務器.cpp : 定義控制臺應用程序的入口點。
//
#include "stdafx.h"
#include <windows.h>
int main()
{
HANDLE hMailSlot = CreateMailslot(
L"\\\\.\\mailslot\\sample",// 郵槽名
0,// 無最大消息限制
MAILSLOT_WAIT_FOREVER,// 永不超時
NULL
);
while (true)
{
DWORD dwCount = 0, dwSize = 0;
GetMailslotInfo(
hMailSlot,// 郵槽名
NULL,// 無最大消息限制
&dwSize,// 下一條消息大小
&dwCount,// 消息個數
NULL);// 永不超時
if (dwSize == MAILSLOT_NO_MESSAGE)
{
Sleep(200);// 暫時沒有消息
continue;
}
while (dwCount)
{
PBYTE pBuf = new BYTE[dwSize+10]{};
ReadFile(hMailSlot, pBuf, dwSize, &dwSize, NULL);
printf("%s\n", pBuf);
GetMailslotInfo(hMailSlot, 0, &dwSize, &dwCount, NULL);
delete[] pBuf;
}
}
return 0;
}