Just a test.高手無視.

服務端:
//Code by Pnig0s1992
//Date:2012,3,19
#include <stdio.h>
#include <Windows.h>
VOID UseMailSlot(LPTSTR lpMailSlotName);
int main(int argc,char **argv)
{
LPTSTR lpSlotName = TEXT("\\\\.\\mailslot\\first_slot");
UseMailSlot(lpSlotName);
return 0;
}
VOID UseMailSlot(LPTSTR lpMailSlotName)
{
HANDLE hMailSlot;
BOOL bResult;
DWORD dwMessageSize;
DWORD dwMessageCount;
DWORD dwHasReadBytes;
hMailSlot = CreateMailslot(lpMailSlotName,0,MAILSLOT_WAIT_FOREVER,NULL);
if(hMailSlot == INVALID_HANDLE_VALUE)
{
printf("\nCreate mailslot:%S failed.",lpMailSlotName);
return;
}else
{
printf("\nCreate mailslot successfully.");
}
int iCount = 0;
int index = 0;
while (1)
{
bResult = GetMailslotInfo(hMailSlot,NULL,&dwMessageSize,&dwMessageCount,NULL);
if(!bResult)
{
printf("\nGetMailslotInfo failed with error:%d",GetLastError());
CloseHandle(hMailSlot);
return;
}
if(dwMessageCount == 0)
{
printf("\nNo.%d wait for message.",iCount+1);
iCount++;
Sleep(2000);
continue;
}
while(dwMessageCount != 0)
{
LPTSTR lpMessageBuffer = (LPTSTR)HeapAlloc(GetProcessHeap
(),HEAP_ZERO_MEMORY,dwMessageSize);
if(lpMessageBuffer == NULL)
{
printf("\nHeapAlloc failed with error:%d",GetLastError());
CloseHandle(hMailSlot);
return;
}
bResult = ReadFile
(hMailSlot,lpMessageBuffer,dwMessageSize,&dwHasReadBytes,NULL);
if(!bResult)
{
printf("\nReadFile failed with error:%d",GetLastError());
HeapFree(GetProcessHeap(),0,lpMessageBuffer);
CloseHandle(hMailSlot);
return;
}
printf("\nReceive No.%d message from client.\nContent:%S",index+1,lpMessageBuffer);
index++;
HeapFree(GetProcessHeap(),0,lpMessageBuffer);
bResult = GetMailslotInfo(hMailSlot,0,&dwMessageSize,&dwMessageCount,NULL);
if(!bResult)
{
printf("\nGetMailslotInfo failed with error:%d",GetLastError());
return;
}
}
}
return;
}
客戶端:
//Code by Pnig0s1992
//Date:2012,3,19
#include <stdio.h>
#include <Windows.h>
VOID ConnectToMailslot(LPTSTR lpMailslotName,LPTSTR lpMessage);
int main(int argc,char ** argv)
{
LPTSTR lpSlotName = TEXT("\\\\.\\mailslot\\first_slot");
LPTSTR lpMessage = TEXT("Test for mailslot communication.");
ConnectToMailslot(lpSlotName,lpMessage);
return 0;
}
VOID ConnectToMailslot(LPTSTR lpMailslotName,LPTSTR lpMessage)
{
HANDLE hFile;
hFile = CreateFile
(lpMailslotName,GENERIC_WRITE,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
if(hFile == INVALID_HANDLE_VALUE)
{
printf("\nCreateFile failed with error:%d",GetLastError());
return;
}
BOOL bResult;
DWORD dwHasWriteBytes;
bResult = WriteFile(hFile,lpMessage,(DWORD)(lstrlen(lpMessage)+1)*sizeof
(TCHAR),&dwHasWriteBytes,NULL);
if(!bResult)
{
printf("\nWriteFile failed with error:%d",GetLastError());
return;
}
printf("Send message to %S successfully.",lpMailslotName);
return;
}
本文出自 “About:Blank H4cking” 博客,請務必保留此出處 http://pnig0s1992.blog.51cto.com/3933