进程间通讯-邮槽服务器与客服端
服务器端
// MialSlotServer1.cpp : 定义控制台应用程序的入口点。
//服务器端
#include "stdafx.h"
#include
#define MAX_BUFFER_LEN 256
//int main(int argc,char* argv[])
int main()
{
HANDLE hSlot;
char buffer[MAX_BUFFER_LEN];
DWORD nReadBytes;
hSlot = CreateMailslot("\\\\.\\Mailslot\\slotSample",0,MAILSLOT_WAIT_FOREVER,NULL);
if(hSlot==INVALID_HANDLE_VALUE)//注意中英文括号的输入-error C2065: “if(hSlot”: 未声明的标识符
//if(hSlot== INVALID_HANDLE_VALUE)
{
printf("创建邮槽失败。错误代码=%d\n",GetLastError());
Sleep(5000);
return 0;
}
printf("检查邮槽。错误代码=%d,0表示无错误\n等待接受邮槽数据...\n", GetLastError());
while (ReadFile(hSlot, buffer, MAX_BUFFER_LEN, &nReadBytes, NULL) != 0)
{
printf("接受到邮槽数据=%.*s\n",nReadBytes,buffer);
}
// Sleep(5000);
return 0;
}
客服端
// MailSlotClient1.cpp : 定义控制台应用程序的入口点。
//客服端
#include "stdafx.h"
#include "process.h"
#include "Windows.h"
int main()
{
HANDLE hSlot;
DWORD dwByteWrite;
char ComputerName[256];
char Content[256];
sprintf(ComputerName,"\\\\.\\Mailslot\\slotSample");
hSlot = CreateFile(ComputerName,GENERIC_WRITE,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if (hSlot == INVALID_HANDLE_VALUE)
{
printf("创建客户端邮槽失败,错误代码=%d\n",GetLastError());
return -1;
}
sprintf(Content,"我是客户端邮槽,向服务器发送测试数据");
if (WriteFile(hSlot, Content, strlen(Content), &dwByteWrite, NULL) == 0)
{
printf("向邮槽写入数据失败。错误代码=%d\n",GetLastError());
return -1;
}
printf("向邮槽写入%d个字节数据\n",dwByteWrite);
CloseHandle(hSlot);
system("pause");
return 0;
return 0;
}