//***************************************************************
// From the book "Win32 System Services: The Heart of Windows 98
// and Windows 2000"
// by Marshall Brain
// Published by Prentice Hall
//
// Copyright 1995, by Prentice Hall.
//
// This code implements a named pipe client.
//***************************************************************

// msnpclnt.cpp

#include <windows.h>
#include <iostream.h>

#define BUFSIZE 128

INT main(VOID)
{
  CHAR textToSend[BUFSIZE];
  CHAR textRecvd[BUFSIZE];
  HANDLE msnpPipe;
  DWORD numBytesRead;
  DWORD numBytesWritten;
  char machineName[80];
  char pipeName[80];

  cout << "Enter name of server machine: ";
  cin.getline(machineName,80);
  wsprintf(pipeName, "\\\\%s\\pipe\\msnp", 
    machineName);

  /* Create the named pipe file handle for
     sending messages */
  msnpPipe=CreateFile(pipeName,
    GENERIC_READ | GENERIC_WRITE,
    0, (LPSECURITY_ATTRIBUTES) NULL,
    OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
    (HANDLE) NULL);

  /* Check and see if the named pipe file was
     opened, if not terminate program */
  if (msnpPipe == INVALID_HANDLE_VALUE)
  {
    cerr << "ERROR: Unable to create a named pipe"
      << endl;
    return (1);
  }

  /* Repeatedly send message until program 
     terminates */
  while(1)
  {
    cout << "Type text to send: ";
    cin.getline(textToSend, BUFSIZE);

    /* Write message to named pipe */
    if (!WriteFile(msnpPipe,
      textToSend, strlen(textToSend) + 1,
      &numBytesWritten, (LPOVERLAPPED) NULL))
    {
      cerr << "ERROR: Unable to write to pipe."
        << endl;
      CloseHandle(msnpPipe);
      return (1);
    }

    if (!ReadFile(msnpPipe,
      textRecvd, BUFSIZE,
      &numBytesRead, (LPOVERLAPPED) NULL))
    {
      cerr << "ERROR: Unable to read from pipe"
        << endl;
      CloseHandle(msnpPipe);
      return (1);
    }

    cout << "Received: " << textRecvd << endl;

  } /* while*/
}
