#include <windows.h> #include <stdio.h> #include <TCHAR.h> #define NUM_PIPES 5 #define BUFFER_SIZE 256 //重叠IO
void main() { HANDLE PipeHandles[NUM_PIPES]; DWORD BytesTransferred; CHAR Buffer[NUM_PIPES][BUFFER_SIZE]; INT i; OVERLAPPED Ovlap[NUM_PIPES]; HANDLE Event[NUM_PIPES];
BOOL DataRead[NUM_PIPES]; DWORD Ret; DWORD Pipe;
for(i=0;i<NUM_PIPES;i++) { if((PipeHandles[i] = CreateNamedPipe(_T("\\\\.\\PIPE\\jim"), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE |PIPE_READMODE_BYTE, NUM_PIPES,0, 0, 1000, NULL))==INVALID_HANDLE_VALUE) { printf("%d\n", GetLastError()); return; }
if((Event[i] = CreateEvent(NULL, TRUE, FALSE, NULL))==NULL) { printf("%d\n", GetLastError()); continue; }
DataRead[i] = FALSE; ZeroMemory(&Ovlap[i], sizeof(OVERLAPPED)); Ovlap[i].hEvent = Event[i];
if(ConnectNamedPipe(PipeHandles[i], &Ovlap[i]) == 0) { if(GetLastError()!=ERROR_IO_PENDING) { printf("%d\n", GetLastError()); CloseHandle(PipeHandles[i]); return; } } } printf("Server is now running\n");
while(1) { if((Ret = WaitForMultipleObjects(NUM_PIPES, Event, FALSE, INFINITE))==WAIT_FAILED) { printf("%d\n", GetLastError()); return; } Pipe = Ret - WAIT_OBJECT_0; ResetEvent(Event[Pipe]);
if(GetOverlappedResult(PipeHandles[Pipe], &Ovlap[Pipe], &BytesTransferred, TRUE) == 0) { printf("%d\n", GetLastError()); if(DisconnectNamedPipe(PipeHandles[Pipe])==0) { printf("%d\n", GetLastError()); return; }
if(ConnectNamedPipe(PipeHandles[Pipe], &Ovlap[Pipe])==0) { if(GetLastError()!=ERROR_IO_PENDING) { printf("%d\n", GetLastError()); CloseHandle(PipeHandles[Pipe]); } }
DataRead[Pipe] = FALSE; } else { if(DataRead[Pipe]==FALSE) { ZeroMemory(&Ovlap[Pipe], sizeof(OVERLAPPED)); Ovlap[Pipe].hEvent = Event[Pipe];
if(ReadFile(PipeHandles[Pipe], Buffer[Pipe], BUFFER_SIZE, NULL, &Ovlap[Pipe])==0) { if(GetLastError() != ERROR_IO_PENDING) { printf("%d\n", GetLastError()); } } DataRead[Pipe]=TRUE; }else { printf("Received %d Bytes, echo bytes back\n", BytesTransferred); ZeroMemory(&Ovlap[Pipe], sizeof(OVERLAPPED)); Ovlap[Pipe].hEvent = Event[Pipe]; if(WriteFile(PipeHandles[Pipe], Buffer[Pipe], BytesTransferred, NULL, &Ovlap[Pipe])==0) { if(GetLastError()!=ERROR_IO_PENDING) { printf("%d\n", GetLastError()); } } DataRead[Pipe] = FALSE; }
} } }
|