服务器:

 #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. 考勤助手ER图2.0版本所存在的问题

    如图所示,考勤助手ER图2.0版本中,缺少个人信箱这一问题虽然不具有逻辑层面的问题,但是它是不满足需求的,也就是说这样的设计无法满足小组对考勤助手最初的设计.其次,就设计层面来分析,弱联系是数据库查询 ...

  2. hadoop 输出中文乱码问题

    本文转载至: http://www.aboutyun.com/thread-7358-1-1.html hadoop涉及输出文本的默认输出编码统一用没有BOM的UTF-8的形式,但是对于中文的输出wi ...

  3. Windows 配置Apache以便在浏览器中运行Python script的CGI模式

    打开httpd.conf,找到”#ScriptInterpreterSource Registry “,移除前面的注释# (如果找不到这行,就自己添加进去) 找到“Options Indexes Fo ...

  4. nodejs mysql 创建连接池

    用Nodejs连接MySQL 从零开始nodejs系列文章,将介绍如何利Javascript做为服务端脚本,通过Nodejs框架web开发.Nodejs框架是基于V8的引擎,是目前速度最快的Javas ...

  5. Qt qobject_cast用法 向下转型

    函数原型: T qobject_cast ( QObject * object ) 本方法返回object向下的转型T,如果转型不成功则返回0,如果传入的object本身就是0则返回0. 在使用时有两 ...

  6. UML类图(一)-------概述+结构

    类图用于描述系统中所包含的类以及它们之间的相互关系,帮助人们简化对系统的理解,它是系统分析和设计阶段的重要产物,也是系统编码和测试的重要模型依据.       1. 类       类(Class)封 ...

  7. 51nod 1428 贪心

    http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1428 1428 活动安排问题 基准时间限制:1 秒 空间限制:13107 ...

  8. 13-THREE.JS 点光源

    <!DOCTYPE html> <html> <head> <title>Example 03.02 - point Light</title&g ...

  9. 条款36:绝对不要重新定义,继承而来的non-virtual函数

    重新定义一个继承而来的non-virtual函数可能会使得导致当函数被调用的时候,被调用的函数不是取决于调用的函数究竟属于的对象,而是取决于调用函数的指针或者引用的类型. 所以一般的说主要有两种观点在 ...

  10. js字符串和数组操作,容易混淆的方法总结(slice、substring、substr、splice)

    平时工作中,很少静下心来总结基础知识,总觉得自己会用了,有点飘了,直到碰壁之后才懂得基础知识的重要性.大牛告诉我,一次写对,是不是可以不用F12去调试了?是不是省了时间?简直是面红耳赤,无地自容.在这 ...