服务器:

 #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. js实现级联菜单(没有后台)

    html代码: <!-- js级联菜单 --> <div id="cascMenu"> <select id="select" o ...

  2. XPath 文档 解析XMl

    http://www.zvon.org/xxl/XPathTutorial/General_chi/examples.html 简介 XPath由W3C的 XPath 1.0 标准描述.本教程通过实例 ...

  3. java文件读写常用方法

    // TODO Auto-generated method stub //File file = new File("D:\\Android\\workspace\\Practice1\\s ...

  4. python基础4 - 判断(if)语句

    6. 判断(if)语句 6.1 if 判断语句基本语法 在 Python 中,if 语句 就是用来进行判断的,格式如下: if 要判断的条件: 条件成立时,要做的事情 …… 注意:代码的缩进为一个 t ...

  5. spring boot: @EnableScheduling开启计划任务支持,@Scheduled计划任务声明

    spring boot: @EnableScheduling开启计划任务支持, @Scheduled计划任务声明 package ch2.scheduler2; //日期转换方式 import jav ...

  6. iTerm2 + Oh My Zsh

    iTerm2 http://iterm2.com/downloads.html https://iterm2.com/downloads/stable/iTerm2-2_1_4.zip Oh My Z ...

  7. RK30SDK开发板驱动分析(一):platform device 的概念与注册

    做过51单片机或者ARM开发的人都知道,单片机内部都有自己的“片内外设”,比如UART,比如I2C,比如SPI等等... 写单片机程序的时候,比如对于UART的驱动,我们都是在程序中直接写一套函数,来 ...

  8. 关于js冒泡、捕获、以及阻止冒泡

    有如下html <ul> <li> <p> <a href="javascript:;">click me</a> &l ...

  9. PhotoShop使用指南(3)—— 将多张图片添加到图层

    第一步:选择文件菜单>脚本>将文件载入堆栈 第二步:点击浏览添加要批量载入的图片

  10. STL迭代器辅助函数——advance

    Advance(i, n) increments the iterator i by the distance n. If n > it it , the call has no effect. ...