recv:
#include <windows.h>
#include <iostream>
int main()
{
HANDLE Mailslot;
char buffer[256];
DWORD NumberOfBytesRead;
// 创建邮件槽
Mailslot = CreateMailslot("\\\\.\\Mailslot\\Myslot",
0,
MAILSLOT_WAIT_FOREVER,
NULL);
if (INVALID_HANDLE_VALUE == Mailslot)
{
printf("Failed to create a mailslot %d/n", GetLastError());
std::cin.get();
return -1;
}
std::cout << "等待接收数据..." << std::endl;
// 从邮件槽上接收数据
while (0 != ReadFile(Mailslot, buffer, 256, &NumberOfBytesRead, NULL))
{
buffer[NumberOfBytesRead] = '\0';
std::cout << "接收的数据大小为:" << NumberOfBytesRead << std::endl;
std::cout << "接收的数据内容为:" << buffer << std::endl;
}
// 关闭邮件槽
CloseHandle(Mailslot);
std::cout << "按任意键退出." << std::endl;
std::cin.get();
return 0;
}
send:
#include <windows.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
HANDLE Mailslot;
DWORD BytesWritten;
CHAR ServerName[256] = {"\\\\.\\Mailslot\\Myslot"};
Mailslot = CreateFile(ServerName, GENERIC_WRITE,
FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (INVALID_HANDLE_VALUE == Mailslot)
{
printf("打开命名邮件槽失败,原因: %d\r\n", GetLastError());
system("pause");
return -1;
}
if (0 == WriteFile(Mailslot, "This is a test", 14, &BytesWritten, NULL))
{
printf("向邮件槽发送数据失败,原因: %d\r\n", GetLastError());
system("pause");
return -1;
}
printf("Wrote %d bytedsr\r\n", BytesWritten);
CloseHandle(Mailslot);
system("pause");
return 0;
}