服务器:

 #include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <strsafe.h> #define BUFSIZE 512 DWORD WINAPI InstanceThread(LPVOID);
VOID GetAnswerToRequest(LPTSTR, LPTSTR, LPDWORD); int _tmain(VOID)
{
BOOL fConnected = FALSE;
DWORD dwThreadId = ;
HANDLE hPipe = INVALID_HANDLE_VALUE, hThread = NULL;
LPTSTR lpszPipename = TEXT("\\\\.\\pipe\\mynamedpipe"); // The main loop creates an instance of the named pipe and
// then waits for a client to connect to it. When the client
// connects, a thread is created to handle communications
// with that client, and this loop is free to wait for the
// next client connect request. It is an infinite loop. for (;;)
{
_tprintf( TEXT("\nPipe Server: Main thread awaiting client connection on %s\n"), lpszPipename);
hPipe = CreateNamedPipe(
lpszPipename, // pipe name
PIPE_ACCESS_DUPLEX, // read/write access
PIPE_TYPE_MESSAGE | // message type pipe
PIPE_READMODE_MESSAGE | // message-read mode
PIPE_WAIT, // blocking mode
PIPE_UNLIMITED_INSTANCES, // max. instances
BUFSIZE, // output buffer size
BUFSIZE, // input buffer size
, // client time-out
NULL); // default security attribute if (hPipe == INVALID_HANDLE_VALUE)
{
_tprintf(TEXT("CreateNamedPipe failed, GLE=%d.\n"), GetLastError());
return -;
} // Wait for the client to connect; if it succeeds,
// the function returns a nonzero value. If the function
// returns zero, GetLastError returns ERROR_PIPE_CONNECTED. //等待客户端接入(目前为阻塞模式)
fConnected = ConnectNamedPipe(hPipe, NULL) ?
TRUE : (GetLastError() == ERROR_PIPE_CONNECTED); if (fConnected)
{
printf("Client connected, creating a processing thread.\n"); // Create a thread for this client.
hThread = CreateThread(
NULL, // no security attribute
, // default stack size
InstanceThread, // thread proc
(LPVOID) hPipe, // thread parameter
, // not suspended
&dwThreadId); // returns thread ID if (hThread == NULL)
{
_tprintf(TEXT("CreateThread failed, GLE=%d.\n"), GetLastError());
return -;
}
else CloseHandle(hThread);
}
else
// The client could not connect, so close the pipe.
CloseHandle(hPipe); } return ;
} DWORD WINAPI InstanceThread(LPVOID lpvParam)
// This routine is a thread processing function to read from and reply to a client
// via the open pipe connection passed from the main loop. Note this allows
// the main loop to continue executing, potentially creating more threads of
// of this procedure to run concurrently, depending on the number of incoming
// client connections.
{
HANDLE hHeap = GetProcessHeap();
TCHAR* pchRequest = (TCHAR*)HeapAlloc(hHeap, , BUFSIZE*sizeof(TCHAR));
TCHAR* pchReply = (TCHAR*)HeapAlloc(hHeap, , BUFSIZE*sizeof(TCHAR)); DWORD cbBytesRead = , cbReplyBytes = , cbWritten = ;
BOOL fSuccess = FALSE;
HANDLE hPipe = NULL; // Do some extra error checking since the app will keep running even if this
// thread fails. if (lpvParam == NULL)
{
printf( "\nERROR - Pipe Server Failure:\n");
printf( " InstanceThread got an unexpected NULL value in lpvParam.\n");
printf( " InstanceThread exitting.\n");
if (pchReply != NULL) HeapFree(hHeap, , pchReply);
if (pchRequest != NULL) HeapFree(hHeap, , pchRequest);
return (DWORD)-;
} if (pchRequest == NULL)
{
printf( "\nERROR - Pipe Server Failure:\n");
printf( " InstanceThread got an unexpected NULL heap allocation.\n");
printf( " InstanceThread exitting.\n");
if (pchReply != NULL) HeapFree(hHeap, , pchReply);
return (DWORD)-;
} if (pchReply == NULL)
{
printf( "\nERROR - Pipe Server Failure:\n");
printf( " InstanceThread got an unexpected NULL heap allocation.\n");
printf( " InstanceThread exitting.\n");
if (pchRequest != NULL) HeapFree(hHeap, , pchRequest);
return (DWORD)-;
} // Print verbose messages. In production code, this should be for debugging only.
printf("InstanceThread created, receiving and processing messages.\n"); // The thread's parameter is a handle to a pipe object instance. hPipe = (HANDLE) lpvParam; // Loop until done reading
while ()
{
// Read client requests from the pipe. This simplistic code only allows messages
// up to BUFSIZE characters in length.
fSuccess = ReadFile(
hPipe, // handle to pipe
pchRequest, // buffer to receive data
BUFSIZE*sizeof(TCHAR), // size of buffer
&cbBytesRead, // number of bytes read
NULL); // not overlapped I/O if (!fSuccess || cbBytesRead == )
{
if (GetLastError() == ERROR_BROKEN_PIPE)
{
_tprintf(TEXT("InstanceThread: client disconnected.\n"), GetLastError());
}
else
{
_tprintf(TEXT("InstanceThread ReadFile failed, GLE=%d.\n"), GetLastError());
}
break;
} // Process the incoming message.
GetAnswerToRequest(pchRequest, pchReply, &cbReplyBytes); // Write the reply to the pipe.
fSuccess = WriteFile(
hPipe, // handle to pipe
pchReply, // buffer to write from
cbReplyBytes, // number of bytes to write
&cbWritten, // number of bytes written
NULL); // not overlapped I/O if (!fSuccess || cbReplyBytes != cbWritten)
{
_tprintf(TEXT("InstanceThread WriteFile failed, GLE=%d.\n"), GetLastError());
break;
}
} // Flush the pipe to allow the client to read the pipe's contents
// before disconnecting. Then disconnect the pipe, and close the
// handle to this pipe instance. FlushFileBuffers(hPipe);
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe); HeapFree(hHeap, , pchRequest);
HeapFree(hHeap, , pchReply); printf("InstanceThread exitting.\n");
return ;
} VOID GetAnswerToRequest( LPTSTR pchRequest,
LPTSTR pchReply,
LPDWORD pchBytes )
// This routine is a simple function to print the client request to the console
// and populate the reply buffer with a default data string. This is where you
// would put the actual client request processing code that runs in the context
// of an instance thread. Keep in mind the main thread will continue to wait for
// and receive other client connections while the instance thread is working.
{
_tprintf( TEXT("Client Request String:\"%S\"\n"), pchRequest );//这里注意大小写的%S,见上一篇随笔 // Check the outgoing message to make sure it's not too long for the buffer.
if (FAILED(StringCchCopy( pchReply, BUFSIZE, TEXT("default answer from server") )))
{
*pchBytes = ;
pchReply[] = ;
printf("StringCchCopy failed, no outgoing message.\n");
return;
}
*pchBytes = (lstrlen(pchReply)+)*sizeof(TCHAR);
}

客户端:

// client.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h> #define BUFSIZE 512 int _tmain(int argc, TCHAR *argv[])
{
HANDLE hPipe;
LPTSTR lpvMessage=TEXT("Default message from client.");
TCHAR chBuf[BUFSIZE];
BOOL fSuccess = FALSE;
DWORD cbRead, cbToWrite, cbWritten, dwMode;
LPTSTR lpszPipename = TEXT("\\\\.\\pipe\\mynamedpipe"); if( argc > )
lpvMessage = argv[]; // Try to open a named pipe; wait for it, if necessary. while ()
{
hPipe = CreateFile(
lpszPipename, // pipe name
GENERIC_READ | // read and write access
GENERIC_WRITE,
, // no sharing
NULL, // default security attributes
OPEN_EXISTING, // opens existing pipe
, // default attributes
NULL); // no template file // Break if the pipe handle is valid. if (hPipe != INVALID_HANDLE_VALUE)
break; // Exit if an error other than ERROR_PIPE_BUSY occurs. if (GetLastError() != ERROR_PIPE_BUSY)
{
_tprintf( TEXT("Could not open pipe. GLE=%d\n"), GetLastError() );
return -;
} // All pipe instances are busy, so wait for 20 seconds. if ( ! WaitNamedPipe(lpszPipename, ))
{
printf("Could not open pipe: 20 second wait timed out.");
return -;
}
} // The pipe connected; change to message-read mode. dwMode = PIPE_READMODE_MESSAGE;
fSuccess = SetNamedPipeHandleState(
hPipe, // pipe handle
&dwMode, // new pipe mode
NULL, // don't set maximum bytes
NULL); // don't set maximum time
if ( ! fSuccess)
{
_tprintf( TEXT("SetNamedPipeHandleState failed. GLE=%d\n"), GetLastError() );
return -;
} // Send a message to the pipe server. cbToWrite = (lstrlen(lpvMessage)+)*sizeof(TCHAR);
_tprintf( TEXT("Sending %d byte message: \"%s\"\n"), cbToWrite, lpvMessage);
//这里的写和读可以用TransactNamedPipe函数来代替,性能更好
fSuccess = WriteFile(
hPipe, // pipe handle
lpvMessage, // message
cbToWrite, // message length
&cbWritten, // bytes written
NULL); // not overlapped if ( ! fSuccess)
{
_tprintf( TEXT("WriteFile to pipe failed. GLE=%d\n"), GetLastError() );
return -;
} printf("\nMessage sent to server, receiving reply as follows:\n"); do
{
// Read from the pipe. fSuccess = ReadFile(
hPipe, // pipe handle
chBuf, // buffer to receive reply
BUFSIZE*sizeof(TCHAR), // size of buffer
&cbRead, // number of bytes read
NULL); // not overlapped if ( ! fSuccess && GetLastError() != ERROR_MORE_DATA )
break; _tprintf( TEXT("\"%S\"\n"), chBuf );
} while ( ! fSuccess); // repeat loop if ERROR_MORE_DATA if ( ! fSuccess)
{
_tprintf( TEXT("ReadFile from pipe failed. GLE=%d\n"), GetLastError() );
return -;
} printf("\n<End of message, press ENTER to terminate connection and exit>");
_getch(); CloseHandle(hPipe); return ;
}

命名管道-MSDN例子的更多相关文章

  1. c#NamedPipe命名管道通信例子

    服务端 private NamedPipeServerStream pipeServer; private Thread receiveDataThread = null; public fServe ...

  2. Linux进程间通信(四):命名管道 mkfifo()、open()、read()、close()

    在前一篇文章—— Linux进程间通信 -- 使用匿名管道 中,我们看到了如何使用匿名管道来在进程之间传递数据,同时也看到了这个方式的一个缺陷,就是这些进程都由一个共同的祖先进程启动,这给我们在不相关 ...

  3. IPC——命名管道

    Linux进程间通信——使用命名管道 转载:http://blog.csdn.net/ljianhui/article/details/10202699 在前一篇文章——Linux进程间通信——使用匿 ...

  4. Linux进程间通信——使用命名管道

    在前一篇文章——Linux进程间通信——使用匿名管道中,我们看到了如何使用匿名管道来在进程之间传递数据,同时也看到了这个方式的一个缺陷,就是这些进程都由一个共同的祖先进程启动,这给我们在不相关的的进程 ...

  5. SQL Server 连接问题-命名管道

    原文:SQL Server 连接问题-命名管道 出自:http://blogs.msdn.com/b/apgcdsd/archive/2011/01/12/sql-server-1.aspx 一.前言 ...

  6. shell 命名管道,进程间通信

    命名管道基础 命名管道也被称为FIFO文件, 在文件系统中是可见的,并且跟其它文件一样可以读写! 命名管道特点: 当写进程向管道中写数据的时候,如果没有进程读取这些数据,写进程会堵塞 当读取管道中的数 ...

  7. Linux环境进程间通信(一):管道及命名管道

    linux下进程间通信的几种主要手段: 管道(Pipe)及有名管道(named pipe):管道可用于具有亲缘关系进程间的通信,有名管道克服了管道没有名字的限制,因此,除具有管道所具有的功能外,它还允 ...

  8. Linux中的pipe(管道)与named pipe(FIFO 命名管道)

    catalogue . pipe匿名管道 . named pipe(FIFO)有名管道 1. pipe匿名管道 管道是Linux中很重要的一种通信方式,是把一个程序的输出直接连接到另一个程序的输入,常 ...

  9. Delphi 简单命名管道在两个进程间通讯

    服务器端代码: unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Control ...

随机推荐

  1. File类之在指定目录中查找文件

    package IoDemo; import java.io.File; /** * @Title:FileDemo2 * @Description:在指定的目录中查找文件 * @author Cra ...

  2. Vue 什么是组件

    Vue.js组件 组件的作用:组件是自定义元素,可扩展html元素,封装可复用的代码. 组件的注册一定要在初始化根实例之前,负责组件是不起作用的. 全局组件在初始化实例的时候被使用 局部组件仅在实例/ ...

  3. hdoj1006--Tick and Tick

    Problem Description The three hands of the clock are rotating every second and meeting each other ma ...

  4. ubuntu安装Qt5

    1.ubuntu 10.04 desktop amd64 问题: 1.1. 没有GLIBCXX_3.4.15版本,或是更高的版本 http://blog.chinaunix.net/uid-91530 ...

  5. libvirt/qemu特性之numa

    博客地址:http://blog.csdn.net/halcyonbaby 内容系本人学习.研究和总结,如有雷同,实属荣幸! Numa 查看主机node情况 使用virsh命令查看 virsh # c ...

  6. phalcon查询:单条查询,多条查询,多表查询

    单条查询, $order = \OrderMain::findFirst("oid='" . $oid . "'"); 多条查询, $shop = \Order ...

  7. 图片文件和Bitmap之间的转换

    图片文件转为Bitmap对象String filePath="c:/01.jpg";  Bitmap bitmap=BitmapFactory.decodeFile(filePat ...

  8. java之 Timer 类的简单使用案例

              (如果您看到本文章务必看结尾!) 第一次用Timer类,记录一下个人理解. 场景:做苹果内容结果验证时,根据苹果支付凭证去苹果官方服务器验证是否支付成功.但因为苹果服务器比较慢,第 ...

  9. 【Prism】MEF版Commanding

    引言 接下来的是Commanding Demo的改造. DelegateCommand    WPF本身提供了一个RoutedCommand,然而没什么卵用.在Prism框架中提供了个更人性化的ICo ...

  10. BuildPipeline.BuildAssetBundle 编译资源包

    原文出自:http://blog.csdn.net/nateyang/article/details/7567831 1.导出.unity3d格式资源: http://game.ceeger.com/ ...