Pipe and Mailslot Creation, Connection, and Naming

Example: A Server That Clients Can Locate
Program 11-3), acting as a mailslot client, uses to broadcast its pipe name to waiting clients. There can be multiple servers with different characteristics and pipe names, and the clients obtain their names from the well-known mailslot name. This function is started as a thread by Program 11-3.Note:
In practice, many client/server systems invert the location logic used here. The alternative is to have the application client also act as the mailslot client and broadcast a message requesting a server to respond on a specified named pipe (the client determines the pipe name and includes that name in the message). The application server, acting as a mailslot server, then reads the request and creates a connection on the specified named pipe.
Program 11-4. SrvrBcst: Mailslot Client Thread Function
Program 11-2) so that it can locate the server.
static DWORD WINAPI ServerBroadcast (LPLONG pNull)
{
MS_MESSAGE MsNotify;
DWORD nXfer;
HANDLE hMsFile;
/* Open the mailslot for the MS "client" writer. */
while (!ShutDown) { /* Run as long as there are server threads. */
/* Wait for another client to open a mailslot. */
Sleep (CS_TIMEOUT);
hMsFile = CreateFile (MS_CLTNAME,
GENERIC_WRITE, FILE_SHARE_READ,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hMsFile == INVALID_HANDLE_VALUE) continue;
/* Send out the message to the mailslot. */
MsNotify.msStatus = 0;
MsNotify.msUtilization = 0;
_tcscpy (MsNotify.msName, SERVER_PIPE);
if (!WriteFile (hMsFile, &MsNotify, MSM_SIZE, &nXfer, NULL))
ReportError (_T ("Server MS Write error."), 13, TRUE);
CloseHandle (hMsFile);
}
_tprintf (_T ("Shutting down monitor thread.\n"));
_endthreadex (0);
return 0;
}
Program 11-5. LocSrver: Mailslot Server
/* Chapter 11. LocSrver.c */
/* Find a server by reading the mailslot
used to broadcast server names. */
#include "EvryThng.h"
#include "ClntSrvr.h" /* Defines mailslot name. */
BOOL LocateServer (LPTSTR pPipeName)
{
HANDLE MsFile;
MS_MESSAGE ServerMsg;
BOOL Found = FALSE;
DWORD cbRead;
MsFile = CreateMailslot (MS_SRVNAME, 0, CS_TIMEOUT, NULL);
while (!Found) {
_tprintf (_T ("Looking for a server.\n"));
Found = ReadFile (MsFile, &ServerMsg, MSM_SIZE,
&cbRead, NULL);
}
_tprintf (_T ("Server has been located.\n"));
CloseHandle (MsFile);
/* Name of the server pipe. */
_tcscpy (pPipeName, ServerMsg.msName);
return TRUE;
}
