调用WinApi实现邮槽通信C/S实例2013-11-27Just 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("
Create mailslot:%S failed.",lpMailSlotName);return;}else{printf("
Create mailslot successfully.");}int iCount = 0;int index = 0;while (1){bResult = GetMailslotInfo(hMailSlot,NULL,&dwMessageSize,&dwMessageCount,NULL);if(!bResult){printf("
GetMailslotInfo failed with error:%d",GetLastError());CloseHandle(hMailSlot);return;}if(dwMessageCount == 0){printf("
No.%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("
HeapAlloc failed with error:%d",GetLastError());CloseHandle(hMailSlot);return;}bResult = ReadFile(hMailSlot,lpMessageBuffer,dwMessageSize,&dwHasReadBytes,NULL);if(!bResult){printf("
ReadFile failed with error:%d",GetLastError());HeapFree(GetProcessHeap(),0,lpMessageBuffer);CloseHandle(hMailSlot);return;}printf("
Receive No.%d message from client.
Content:%S",index+1,lpMessageBuffer);index++;HeapFree(GetProcessHeap(),0,lpMessageBuffer);bResult = GetMailslotInfo(hMailSlot,0,&dwMessageSize,&dwMessageCount,NULL);if(!bResult){printf("
GetMailslotInfo failed with error:%d",GetLastError());return;}}}return;}