The following is an example of a
single-threaded pipe server that uses overlapped operations to service
simultaneous connections to multiple pipe clients. The pipe server creates a
fixed number of pipe instances. Each pipe instance can be connected to a
separate pipe client. When a pipe client has finished using its pipe instance,
the server disconnects from the client and reuses the pipe instance to connect
to a new client. This pipe server can be used with the pipe client described in
Named Pipe Client
.
The OVERLAPPED
structure is specified as a
parameter in each ReadFile
, WriteFile
, and ConnectNamedPipe
operation on the pipe
instance. Although the example shows simultaneous operations on different pipe
instances, it avoids simultaneous operations on a single pipe instance by using
the event object in the OVERLAPPED
structure. Because the same event
object is used for read, write, and connect operations for each instance, there
is no way to know which operation's completion caused the event to be set to
the signaled state for simultaneous operations using the same pipe instance.
The event handles for each pipe
instance are stored in an array that is passed to the WaitForMultipleObjects
function. This function
waits for one of the events to be signaled, and returns the array index of the
event that caused the wait operation to complete. The example in this topic
uses this array index to retrieve a structure containing information for the
pipe instance. The server uses the fPendingIO
member of the structure to
keep track of whether the most recent I/O operation on the instance was
pending, which requires a call to the GetOverlappedResult
function. The server uses
the dwState
member of the structure to determine the next operation that
must be performed for the pipe instance.
Overlapped ReadFile
, WriteFile
,
and ConnectNamedPipe
operations can finish by the time the function
returns. Otherwise, if the operation is pending, the event object in the
specified OVERLAPPED
structure is set to the nonsignaled state before
the function returns. When the pending operation finishes, the system sets the
state of the event object to signaled. The state of the event object is not
changed if the operation finishes before the function returns.
Because the example uses
manual-reset event objects, the state of an event object is not changed to
nonsignaled by the WaitForMultipleObjects
function. This is important,
because the example relies on the event objects remaining in the signaled
state, except when there is a pending operation.
If the operation has already
finished when ReadFile
, WriteFile
, or ConnectNamedPipe
returns, the function's
return value indicates the result. For read and write operations, the number of
bytes transferred is also returned. If the operation is still pending, the ReadFile
,
WriteFile
, or ConnectNamedPipe
function returns zero and the GetLastError
function returns
ERROR_IO_PENDING. In this case, use the GetOverlappedResult
function to
retrieve the results after the operation has finished. GetOverlappedResult
returns only the results of pending operations. It does not report the results
of operations that were completed before the overlapped ReadFile
, WriteFile
,
or ConnectNamedPipe
function returned.
Before disconnecting from a client,
you must wait for a signal indicating the client has finished. (Flushing the
file buffers would defeat the purpose of overlapped I/O, because the flush
operation would block the execution of the server thread while it waits for the
client to empty the pipe.) In this example, the signal is the error generated
by trying to read from the pipe after the pipe client closes its handle.
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <strsafe.h>
#define CONNECTING_STATE 0
#define READING_STATE 1
#define WRITING_STATE 2
#define INSTANCES 4
#define PIPE_TIMEOUT 5000
#define BUFSIZE 4096
typedef struct
{
OVERLAPPED oOverlap;
HANDLE hPipeInst;
TCHAR chRequest[BUFSIZE];
DWORD cbRead;
TCHAR chReply[BUFSIZE];
DWORD cbToWrite;
DWORD dwState;
BOOL fPendingIO;
} PIPEINST, *LPPIPEINST;
VOID DisconnectAndReconnect(DWORD);
BOOL ConnectToNewClient(HANDLE, LPOVERLAPPED);
VOID GetAnswerToRequest(LPPIPEINST);
PIPEINST Pipe[INSTANCES];
HANDLE hEvents[INSTANCES];
int _tmain(VOID)
{
DWORD i, dwWait, cbRet, dwErr;
BOOL fSuccess;
LPTSTR lpszPipename = TEXT("\\\\.\\pipe\\mynamedpipe");
// The initial loop creates several instances of a named pipe
// along with an event object for each instance. An
// overlapped ConnectNamedPipe operation is started for
// each instance.
for (i = 0; i < INSTANCES; i++)
{
// Create an event object for this instance.
hEvents[i] = CreateEvent(
NULL, // default security attribute
TRUE, // manual-reset event
TRUE, // initial state = signaled
NULL); // unnamed event object
if (hEvents[i] == NULL)
{
printf("CreateEvent failed with %d.\n", GetLastError());
return 0;
}
Pipe[i].oOverlap.hEvent = hEvents[i];
Pipe[i].hPipeInst = CreateNamedPipe(
lpszPipename, // pipe name
PIPE_ACCESS_DUPLEX | // read/write access
FILE_FLAG_OVERLAPPED, // overlapped mode
PIPE_TYPE_MESSAGE | // message-type pipe
PIPE_READMODE_MESSAGE | // message-read mode
PIPE_WAIT, // blocking mode
INSTANCES, // number of instances
BUFSIZE*sizeof(TCHAR), // output buffer size
BUFSIZE*sizeof(TCHAR), // input buffer size
PIPE_TIMEOUT, // client time-out
NULL); // default security attributes
if (Pipe[i].hPipeInst == INVALID_HANDLE_VALUE)
{
printf("CreateNamedPipe failed with %d.\n", GetLastError());
return 0;
}
// Call the subroutine to connect to the new client
Pipe[i].fPendingIO = ConnectToNewClient(
Pipe[i].hPipeInst,
&Pipe[i].oOverlap);
Pipe[i].dwState = Pipe[i].fPendingIO ?
CONNECTING_STATE : // still connecting
READING_STATE; // ready to read
}
while (1)
{
// Wait for the event object to be signaled, indicating
// completion of an overlapped read, write, or
// connect operation.
dwWait = WaitForMultipleObjects(
INSTANCES, // number of event objects
hEvents, // array of event objects
FALSE, // does not wait for all
INFINITE); // waits indefinitely
// dwWait shows which pipe completed the operation.
i = dwWait - WAIT_OBJECT_0; // determines which pipe
if (i < 0 || i > (INSTANCES - 1))
{
printf("Index out of range.\n");
return 0;
}
// Get the result if the operation was pending.
if (Pipe[i].fPendingIO)
{
fSuccess = GetOverlappedResult(
Pipe[i].hPipeInst, // handle to pipe
&Pipe[i].oOverlap, // OVERLAPPED structure
&cbRet, // bytes transferred
FALSE); // do not wait
switch (Pipe[i].dwState)
{
// Pending connect operation
case CONNECTING_STATE:
if (! fSuccess)
{
printf("Error %d.\n", GetLastError());
return 0;
}
Pipe[i].dwState = READING_STATE;
break;
// Pending read operation
case READING_STATE:
if (! fSuccess || cbRet == 0)
{
DisconnectAndReconnect(i);
continue;
}
Pipe[i].dwState = WRITING_STATE;
break;
// Pending write operation
case WRITING_STATE:
if (! fSuccess || cbRet != Pipe[i].cbToWrite)
{
DisconnectAndReconnect(i);
continue;
}
Pipe[i].dwState = READING_STATE;
break;
default:
{
printf("Invalid pipe state.\n");
return 0;
}
}
}
// The pipe state determines which operation to do next.
switch (Pipe[i].dwState)
{
// READING_STATE:
// The pipe instance is connected to the client
// and is ready to read a request from the client.
case READING_STATE:
fSuccess = ReadFile(
Pipe[i].hPipeInst,
Pipe[i].chRequest,
BUFSIZE*sizeof(TCHAR),
&Pipe[i].cbRead,
&Pipe[i].oOverlap);
// The read operation completed successfully.
if (fSuccess && Pipe[i].cbRead != 0)
{
Pipe[i].fPendingIO = FALSE;
Pipe[i].dwState = WRITING_STATE;
continue;
}
// The read operation is still pending.
dwErr = GetLastError();
if (! fSuccess && (dwErr == ERROR_IO_PENDING))
{
Pipe[i].fPendingIO = TRUE;
continue;
}
// An error occurred; disconnect from the client.
DisconnectAndReconnect(i);
break;
// WRITING_STATE:
// The request was successfully read from the client.
// Get the reply data and write it to the client.
case WRITING_STATE:
GetAnswerToRequest(&Pipe[i]);
fSuccess = WriteFile(
Pipe[i].hPipeInst,
Pipe[i].chReply,
Pipe[i].cbToWrite,
&cbRet,
&Pipe[i].oOverlap);
// The write operation completed successfully.
if (fSuccess && cbRet == Pipe[i].cbToWrite)
{
Pipe[i].fPendingIO = FALSE;
Pipe[i].dwState = READING_STATE;
continue;
}
// The write operation is still pending.
dwErr = GetLastError();
if (! fSuccess && (dwErr == ERROR_IO_PENDING))
{
Pipe[i].fPendingIO = TRUE;
continue;
}
// An error occurred; disconnect from the client.
DisconnectAndReconnect(i);
break;
default:
{
printf("Invalid pipe state.\n");
return 0;
}
}
}
return 0;
}
// DisconnectAndReconnect(DWORD)
// This function is called when an error occurs or when the client
// closes its handle to the pipe. Disconnect from this client, then
// call ConnectNamedPipe to wait for another client to connect.
VOID DisconnectAndReconnect(DWORD i)
{
// Disconnect the pipe instance.
if (! DisconnectNamedPipe(Pipe[i].hPipeInst) )
{
printf("DisconnectNamedPipe failed with %d.\n", GetLastError());
}
// Call a subroutine to connect to the new client.
Pipe[i].fPendingIO = ConnectToNewClient(
Pipe[i].hPipeInst,
&Pipe[i].oOverlap);
Pipe[i].dwState = Pipe[i].fPendingIO ?
CONNECTING_STATE : // still connecting
READING_STATE; // ready to read
}
// ConnectToNewClient(HANDLE, LPOVERLAPPED)
// This function is called to start an overlapped connect operation.
// It returns TRUE if an operation is pending or FALSE if the
// connection has been completed.
BOOL ConnectToNewClient(HANDLE hPipe, LPOVERLAPPED lpo)
{
BOOL fConnected, fPendingIO = FALSE;
// Start an overlapped connection for this pipe instance.
fConnected = ConnectNamedPipe(hPipe, lpo);
// Overlapped ConnectNamedPipe should return zero.
if (fConnected)
{
printf("ConnectNamedPipe failed with %d.\n", GetLastError());
return 0;
}
switch (GetLastError())
{
// The overlapped connection in progress.
case ERROR_IO_PENDING:
fPendingIO = TRUE;
break;
// Client is already connected, so signal an event.
case ERROR_PIPE_CONNECTED:
if (SetEvent(lpo->hEvent))
break;
// If an error occurs during the connect operation...
default:
{
printf("ConnectNamedPipe failed with %d.\n", GetLastError());
return 0;
}
}
return fPendingIO;
}
VOID GetAnswerToRequest(LPPIPEINST pipe)
{
_tprintf( TEXT("[%d] %s\n"), pipe->hPipeInst, pipe->chRequest);
StringCchCopy( pipe->chReply, BUFSIZE, TEXT("Default answer from server") );
pipe->cbToWrite = (lstrlen(pipe->chReply)+1)*sizeof(TCHAR);
}
分享到:
相关推荐
本文将详细介绍当前Windows系统中支持的各种Socket I/O模型,包括select、WSAAsyncSelect、WSAEventSelect、Overlapped I/O(重叠IO模型)以及IOCP模型,并通过代码示例来进一步解释它们的工作原理及应用场景。...
在本文中,我们将深入探讨异步Socket I/O模型的几种常见实现方式,包括选择(select)、异步选择(asynchronous select)、事件选择(poll)、重叠I/O(overlapped I/O)以及完成端口(completion ports)。...
重叠I/O模型是一种非阻塞I/O模型,通过使用`OVERLAPPED`结构来异步执行I/O操作。这种方式非常适合高并发场景。 **示例代码:** ```c // 创建重叠结构 OVERLAPPED ovl; ZeroMemory(&ovl, sizeof(OVERLAPPED)); // ...
重叠I/O是一种在Windows操作系统中实现异步通信的技术,它允许I/O操作与执行其他系统调用同时进行,从而极大地提高了系统效率和程序的并发性能。在这个项目中,我们有一个名为“LappedSocket”的类,它封装了重叠I/O...
例如,Windows的` overlapped I/O`和Linux的`epoll`。 4. **错误处理**:I/O操作可能会遇到各种问题,如文件不存在、权限不足、设备故障等。I/O库通常会提供错误检测和报告机制,帮助开发者定位并解决问题。 5. **...
此外,OVERLAPPED结构体用于存储I/O操作的相关信息,包括偏移量和异步操作的状态。 7. **资源管理**: 在处理大量I/O请求时,内存管理和线程池的使用至关重要。合理的资源分配和复用可以避免内存泄漏,同时确保...
重叠I/O(Overlapped I/O)是Windows操作系统中的一种高效I/O操作模型,它允许数据传输与其他处理任务在同一个线程中并发执行,从而提高系统资源利用率和程序性能。这种模型通常与事件通知机制结合,如Windows的内核...
在本压缩包"Overlapped-IO-model-based-server.rar"中,包含了一个基于重叠I/O的服务器程序,该程序设计的目标是能同时处理成千上万个连接,其性能接近于使用完成端口(Completion Port)的服务器。 首先,理解重叠...
5. **处理I/O完成**:当`GetQueuedCompletionStatus`返回时,它会携带I/O操作的结果信息,包括完成状态、传输的字节数以及一个用户提供的标识符(如OVERLAPPED结构体的指针),你可以根据这些信息进行相应的业务处理...
Windows操作系统提供了选择(Select)、异步选择 (WSAAsyncSelect)、事件选择(WSAEventSelect)、重叠I/O(Overlapped I/O)和完成端口(Completion Port)共五种I/O模型。每一种模型均适用于一种特定的应用场景。...
本文将深入探讨如何使用C++实现采用事件通知的socket重叠I/O模型,这一模型在处理大量并发连接时具有显著优势。 首先,我们需要理解“重叠I/O”(又称异步I/O)的概念。在传统的同步I/O模型中,一个调用会阻塞直到I...
Windows操作系统提供了五种I/O模型:选择模型(Select)、异步选择模型(WSAAsyncSelect)、事件选择模型(WSAEventSelect)、重叠I/O模型(Overlapped I/O)和完成端口模型(Completion Port)。每一种模型都适用于...
重叠I/O(Overlapped I/O)是一种在Windows操作系统中实现高效网络编程的技术,它允许数据传输与其他操作同时进行,极大地提高了系统处理能力。基于完成例程的重叠I/O模型是这种技术的一种实现方式,它通过回调函数...
利用Visual C++ 6.0实现的一套Winsock I/O模型,包括了所有的Winsock I/O模型:Select模型、AsyncSelect(异步选择模型)、EventSelect(事件选择模型)、Overlapped(重叠模型)、CompletionRoutine(完成例程)、...
在这个"C++ Tutorial: Sockets - Server & Client using QT - 2015"中,你将学习到如何利用QT的网络模块来实现基于TCP的通信。 首先,我们来看看QT中的`QTcpServer`类,它是用于创建服务器端应用的核心组件。`...
4. **重叠I/O(Overlapped I/O)** - **原理**:重叠I/O是Windows系统提供的高级异步I/O模型,它允许I/O操作在发出后立即返回,而无需等待操作完成。 - **使用结构**:使用`OVERLAPPED`结构体记录I/O操作的状态,并...
在Windows操作系统中,重叠I/O(Overlapped I/O)是一种高级的I/O机制,它允许多个I/O操作并发地在单个线程上执行,而无需等待每个操作完成。这种技术对于构建高性能的客户端/服务器应用程序至关重要,因为它可以极...
**重叠I/O模型**(Overlapped I/O Model)是另一种高效的处理方式。在该模型中,I/O操作是非阻塞的,可以与其他操作并行进行。通过使用OVERLAPPED结构,系统可以在后台完成I/O操作,而主线程则可以继续执行其他任务...
4. **异步I/O(Asynchronous I/O)**:如上所述的Overlapped I/O模型就是一种异步I/O实现,允许应用程序提交I/O操作后立即返回,而不必等待操作完成,从而提高程序的并发性和响应性。 ### 示例代码分析 文档中还...