THRIFT-1558 Named Pipe and Anonymous Pipe transport for Windows
Patch: Peace
add pipe crossplatform example to contrib

git-svn-id: https://svn.apache.org/repos/asf/thrift/trunk@1351477 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/contrib/transport-sample/client/ReadMe.txt b/contrib/transport-sample/client/ReadMe.txt
new file mode 100644
index 0000000..6c49a96
--- /dev/null
+++ b/contrib/transport-sample/client/ReadMe.txt
@@ -0,0 +1,40 @@
+========================================================================
+    CONSOLE APPLICATION : client Project Overview
+========================================================================
+
+AppWizard has created this client application for you.
+
+This file contains a summary of what you will find in each of the files that
+make up your client application.
+
+
+client.vcxproj
+    This is the main project file for VC++ projects generated using an Application Wizard.
+    It contains information about the version of Visual C++ that generated the file, and
+    information about the platforms, configurations, and project features selected with the
+    Application Wizard.
+
+client.vcxproj.filters
+    This is the filters file for VC++ projects generated using an Application Wizard. 
+    It contains information about the association between the files in your project 
+    and the filters. This association is used in the IDE to show grouping of files with
+    similar extensions under a specific node (for e.g. ".cpp" files are associated with the
+    "Source Files" filter).
+
+client.cpp
+    This is the main application source file.
+
+/////////////////////////////////////////////////////////////////////////////
+Other standard files:
+
+StdAfx.h, StdAfx.cpp
+    These files are used to build a precompiled header (PCH) file
+    named client.pch and a precompiled types file named StdAfx.obj.
+
+/////////////////////////////////////////////////////////////////////////////
+Other notes:
+
+AppWizard uses "TODO:" comments to indicate parts of the source code you
+should add to or customize.
+
+/////////////////////////////////////////////////////////////////////////////
diff --git a/contrib/transport-sample/client/client.cpp b/contrib/transport-sample/client/client.cpp
new file mode 100644
index 0000000..45fbef1
--- /dev/null
+++ b/contrib/transport-sample/client/client.cpp
@@ -0,0 +1,195 @@
+// client->cpp : Defines the entry point for the console application.
+//
+// sample client command line app using Thrift IPC.
+// Quick n Dirty example, may not have very robust error handling
+// for the sake of simplicity.
+
+#ifdef _WIN32
+#  include "stdafx.h"
+#else
+#  include "config.h"
+#endif
+
+
+//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+//Include this before the generated includes
+#include "ThriftCommon.h"
+//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+//Tailor these to your generated files
+#include "../gen-cpp/SampleService.h"
+#include "../gen-cpp/SampleCallback.h"
+
+using namespace Sample; //declared in .thrift file
+//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+void ClientListenerThreadProc();
+bool bSocket = false;
+bool bAnonPipe = false;
+int srvPort;
+std::string pipename;
+std::string pipename_client;
+#ifdef _WIN32
+ HANDLE hConsole;
+#endif
+
+//Customized version of printf that changes the text color
+//This depends on hConsole global being initialized
+void hlprintf(const char* _Format, ...)
+{
+#ifdef _WIN32
+	SetConsoleTextAttribute(hConsole, 0xE);
+#endif
+	va_list ap;
+	int r;
+	va_start (ap, _Format);
+	r = vprintf (_Format, ap);
+	va_end (ap);
+#ifdef _WIN32
+	SetConsoleTextAttribute(hConsole, 7);
+#endif
+}
+
+//-----------------------------------------------------------------------------
+// Client-side RPC implementations: Called by the server to the client for 
+// bidirectional eventing.
+//
+class SampleCallbackHandler : virtual public SampleCallbackIf {
+ public:
+  SampleCallbackHandler() {
+    // initialization goes here
+  }
+
+  void pingclient()
+  {
+    hlprintf("<<<Ping received from server (server-to-client event).\n");
+  }
+
+};
+//-----------------------------------------------------------------------------
+
+
+#ifdef _WIN32
+int _tmain(int argc, _TCHAR* argv[])
+#else
+int main(int argc, char **argv)
+#endif
+{
+	//Process cmd line args to determine named vs anon pipes.
+	bool usage = false;
+#ifdef _WIN32
+	HANDLE ReadPipe, WritePipe;
+	hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
+#endif
+
+	//Process command line params
+	if(argc > 1)
+	{
+		if(_tcscmp(argv[1], TEXT("-sp")) == 0)
+		{	//Socket Port specified
+			srvPort = _tstoi(argv[2]);
+			bSocket = true;
+		}
+		else if(_tcscmp(argv[1], TEXT("-np")) == 0)
+		{	//Named Pipe specified
+#ifdef _WIN32
+                        std::wstring wpipe(argv[2]);
+                        pipename.resize(wpipe.length());
+                        std::copy(wpipe.begin(), wpipe.end(), pipename.begin());
+#else
+                        pipename = argv[2];
+#endif
+			pipename_client = pipename + "_client";
+		}
+		else if(argc == 3)
+		{	//Anonymous Pipe specified
+#ifdef _WIN32
+			ReadPipe  = (HANDLE)_tstoi(argv[1]);
+			WritePipe = (HANDLE)_tstoi(argv[2]);
+			bAnonPipe = true;
+#else
+                        printf("Anonymous pipes not (yet) supported under *NIX\n");
+#endif
+		}
+		else
+			usage = true;
+	}
+	else
+		usage = true;
+
+	if(usage)
+	{
+		hlprintf("Thrift sample client usage:\n\n");
+		hlprintf("Socket Port to connect to: -sp <port#>\n");
+		hlprintf("Named Pipe to connect to:  -np <pipename> (e.g. affpipe)\n");
+		hlprintf("Anonymous Pipe (must be launched by anon pipe creator):\n");
+		hlprintf("                           <Read Handle> <Write Handle>\n");
+		return 0;
+	}
+
+	//Client side connection to server.
+	boost::shared_ptr<SampleServiceClient> client; //Client class from Thrift-generated code.
+	boost::shared_ptr<TTransport> transport;
+
+	if(bSocket)
+	{	//Socket transport
+#ifdef _WIN32
+		TWinsockSingleton::create();
+#endif
+		hlprintf("Using socket transport port %d\n", srvPort);
+		thriftcommon::ConnectToServer<SampleServiceClient, TTransport>(client, transport, srvPort);
+	}
+	else if(!bAnonPipe)
+	{
+		hlprintf("Using Named Pipe %s\n", pipename.c_str());
+		thriftcommon::ConnectToServer<SampleServiceClient, TTransport>(client, transport, pipename);
+	}
+	else
+	{
+#ifdef _WIN32
+		hlprintf("Using Anonymous Pipe transport\n");
+		thriftcommon::ConnectToServer<SampleServiceClient, TTransport>(client, transport, ReadPipe, WritePipe);
+#endif
+	}
+
+#ifdef _WIN32
+	//Start a thread to receive inbound connection from server for 2-way event signaling.
+	boost::thread ClientListenerThread(ClientListenerThreadProc);
+#endif
+
+	try {
+		transport->open();
+
+		//Notify server what to connect back on.
+		if(bSocket)
+			client->ClientSideListenPort(srvPort + 1); //Socket
+		else if(!bAnonPipe)
+			client->ClientSidePipeName(pipename_client); //Named Pipe
+
+		//Run some more RPCs
+		std::string hellostr = "Hello how are you?";
+		std::string returnstr;
+		client->HelloThere(returnstr, hellostr);
+		hlprintf("\n>>>Sent: %s\n", hellostr.c_str());
+		hlprintf("<<<Received: %s\n", returnstr.c_str());
+
+		hlprintf("\n>>>Calling ServerDoSomething() which delays for 5 seconds.\n");
+		client->ServerDoSomething();
+		hlprintf(">>>ServerDoSomething() done.\n\n");
+
+		transport->close();
+	} catch (TException &tx) {
+		hlprintf("ERROR: %s\n", tx.what());
+	}
+
+	return 0;
+}
+
+
+//Thread Routine
+void ClientListenerThreadProc()
+{
+	if(bSocket)
+		thriftcommon::RunThriftServer<SampleCallbackHandler, SampleCallbackProcessor>(1, srvPort + 1);
+	else if(!bAnonPipe)
+		thriftcommon::RunThriftServer<SampleCallbackHandler, SampleCallbackProcessor>(1, pipename_client);
+}
diff --git a/contrib/transport-sample/client/client.vcxproj b/contrib/transport-sample/client/client.vcxproj
new file mode 100644
index 0000000..779c339
--- /dev/null
+++ b/contrib/transport-sample/client/client.vcxproj
@@ -0,0 +1,105 @@
+?<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{85FBFB54-530B-498F-9F38-44BA204FAE6A}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>client</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <LinkIncremental>true</LinkIncremental>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <LinkIncremental>false</LinkIncremental>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../;../../../lib/cpp/src;../../../../boost;../../../../boost/boost/tr1;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <AdditionalLibraryDirectories>../../../lib/cpp/$(Configuration);../../../../Boost/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+      <AdditionalDependencies>libthrift.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+      <AdditionalIncludeDirectories>../;../../../lib/cpp/src;../../../../boost;../../../../boost/boost/tr1;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+      <AdditionalLibraryDirectories>../../../lib/cpp/$(Configuration);../../../../Boost/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+      <AdditionalDependencies>libthrift.lib;ws2_32.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <None Include="ReadMe.txt" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="..\gen-cpp\SampleCallback.h" />
+    <ClInclude Include="..\gen-cpp\SampleService.h" />
+    <ClInclude Include="..\gen-cpp\Sample_constants.h" />
+    <ClInclude Include="..\gen-cpp\Sample_types.h" />
+    <ClInclude Include="stdafx.h" />
+    <ClInclude Include="targetver.h" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\ThriftCommon.cpp" />
+    <ClCompile Include="..\gen-cpp\SampleCallback.cpp" />
+    <ClCompile Include="..\gen-cpp\SampleService.cpp" />
+    <ClCompile Include="..\gen-cpp\Sample_constants.cpp" />
+    <ClCompile Include="..\gen-cpp\Sample_types.cpp" />
+    <ClCompile Include="client.cpp" />
+    <ClCompile Include="stdafx.cpp" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/contrib/transport-sample/client/client.vcxproj.filters b/contrib/transport-sample/client/client.vcxproj.filters
new file mode 100644
index 0000000..3ec7bde
--- /dev/null
+++ b/contrib/transport-sample/client/client.vcxproj.filters
@@ -0,0 +1,66 @@
+?<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+    <Filter Include="Resource Files">
+      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
+    </Filter>
+    <Filter Include="Source Files\gen-cpp">
+      <UniqueIdentifier>{1265b3dc-91de-416f-aba6-7b750de4221e}</UniqueIdentifier>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="ReadMe.txt" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="stdafx.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="targetver.h">
+      <Filter>Header Files</Filter>
+    </ClInclude>
+    <ClInclude Include="..\gen-cpp\Sample_types.h">
+      <Filter>Source Files\gen-cpp</Filter>
+    </ClInclude>
+    <ClInclude Include="..\gen-cpp\SampleService.h">
+      <Filter>Source Files\gen-cpp</Filter>
+    </ClInclude>
+    <ClInclude Include="..\gen-cpp\Sample_constants.h">
+      <Filter>Source Files\gen-cpp</Filter>
+    </ClInclude>
+    <ClInclude Include="..\gen-cpp\SampleCallback.h">
+      <Filter>Source Files\gen-cpp</Filter>
+    </ClInclude>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="stdafx.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="client.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+    <ClCompile Include="..\gen-cpp\SampleService.cpp">
+      <Filter>Source Files\gen-cpp</Filter>
+    </ClCompile>
+    <ClCompile Include="..\gen-cpp\Sample_constants.cpp">
+      <Filter>Source Files\gen-cpp</Filter>
+    </ClCompile>
+    <ClCompile Include="..\gen-cpp\Sample_types.cpp">
+      <Filter>Source Files\gen-cpp</Filter>
+    </ClCompile>
+    <ClCompile Include="..\gen-cpp\SampleCallback.cpp">
+      <Filter>Source Files\gen-cpp</Filter>
+    </ClCompile>
+    <ClCompile Include="..\ThriftCommon.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+</Project>
diff --git a/contrib/transport-sample/client/stdafx.cpp b/contrib/transport-sample/client/stdafx.cpp
new file mode 100644
index 0000000..4bd151e
--- /dev/null
+++ b/contrib/transport-sample/client/stdafx.cpp
@@ -0,0 +1,8 @@
+// stdafx.cpp : source file that includes just the standard includes
+// client.pch will be the pre-compiled header
+// stdafx.obj will contain the pre-compiled type information
+
+#include "stdafx.h"
+
+// TODO: reference any additional headers you need in STDAFX.H
+// and not in this file
diff --git a/contrib/transport-sample/client/stdafx.h b/contrib/transport-sample/client/stdafx.h
new file mode 100644
index 0000000..b005a83
--- /dev/null
+++ b/contrib/transport-sample/client/stdafx.h
@@ -0,0 +1,15 @@
+// stdafx.h : include file for standard system include files,
+// or project specific include files that are used frequently, but
+// are changed infrequently
+//
+
+#pragma once
+
+#include "targetver.h"
+
+#include <stdio.h>
+#include <tchar.h>
+
+
+
+// TODO: reference additional headers your program requires here
diff --git a/contrib/transport-sample/client/targetver.h b/contrib/transport-sample/client/targetver.h
new file mode 100644
index 0000000..87c0086
--- /dev/null
+++ b/contrib/transport-sample/client/targetver.h
@@ -0,0 +1,8 @@
+#pragma once
+
+// Including SDKDDKVer.h defines the highest available Windows platform.
+
+// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and
+// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h.
+
+#include <SDKDDKVer.h>