NAMEDPIPE CLIENT/SERVER IPC CLASS
INTRODUCTION
The CNamedPipeHost and CNamedPipeClient classes are two classes I have used in more than one project of mine in the past. They should be enough tested for being used with confidence in other projects as well. If you have suggestions and/or corrections about these implementations, please feel free to write to me.
They are intended expressly for client/server IPC purposes: in fact the server code waits and accepts only one connection from the corresponding peer. If you want to enable multiple CNamedPipeClients to connect to a single instance of a CNamedPipeHost, then you should modify opportunely the server implementation: the changes required in the CNamedPipeHost class in order to enable multiple client connections should be less than complex or extensive. As you may already know, named pipes created with the PIPE_TYPE_MESSAGE flag are message-based: this can be a very convenient solution over a corresponding TCP socket channel in the case when the nature of the protocol transported requires that the message boundaries have to be preserved.
TYPE DEFINITION DETAILS
class CNamedPipeHost
{
// construction.
CNamedPipeHost( charstring& strPipeName, PFNRECV pfnRecvCallback, int iRecvBufferSize, DWORD dwRecvCallbackParam, PFNCLOSE pfnCloseCallback = NULL );
// methods.
BOOL StartListening ();
int Send ( CONST BYTE* pbBuffer, int nBufferSize );
VOID DisconnectClient ();
};
class CNamedPipeClient
{
// construction.
CNamedPipeClient ( charstring& strPipeName, PFNRECV pfnRecvCallback, int iRecvBufferSize, DWORD dwRecvCallbackParam, PFNCLOSE pfnCloseCallback = NULL );
// methods.
BOOL Connect ();
void Disconnect ( BOOL reserved = TRUE );
VOID SetRecvCallbackParam( DWORD dwRecvCallbackParam );
int Send ( CONST BYTE* pbBuffer, int nBufferSize );
// properties.
BOOL IsConnected ();
};
HOW TO USE
Simply instantiate the correct class (CNamedPipeHost when creating a named pipe server and CNamedPipeClient when creating a client) and then call the StartListening or the Connect method respectively.
REQUIRED DEFINITIONS
All my IPC classes use STL under the hood. Be sure to include the following definitions BEFORE the definitions of all my IPC types:
// Stl Stuff.
#include <string>
#include <vector>
#include <map>
typedef std::basic_string< CHAR > charstring;
typedef std::vector< charstring > charstring_vector;
typedef std::basic_string< WCHAR > widestring;
typedef std::vector< widestring > widestring_vector;
ACTUAL CODE
NamePipe_code.h
|