Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Windows.h>
- #include <iostream>
- #include <string>
- using namespace std;
- #define BUFFER_SIZE 256
- #define PipeSize 256
- #define PIPE_INSTANCES 10
- #define NamePipe "\\\\.\\pipe\\pipe"
- #define NameEvent "pipeEvent"
- // структура-описатель одного подключения
- struct PIPE_INFO
- {
- HANDLE hPipe;
- OVERLAPPED o;
- BOOL bConnected;
- char buf[BUFFER_SIZE];
- };
- // вектор подключений
- PIPE_INFO pPipes[PIPE_INSTANCES];
- // вектор событий для мониторинга ввода-вывода
- HANDLE pEvents[PIPE_INSTANCES];
- ///////////////////////////////////////////////////////
- // функция переустановления соединения
- void ReconnectPipe(int iIndex)
- {
- // если подключение осуществлено
- if (pPipes[iIndex].bConnected)
- {
- // закрытие соединения
- pPipes[iIndex].bConnected = FALSE;
- DisconnectNamedPipe(pPipes[iIndex].hPipe);
- }
- // инициализация нового соединения
- BOOL bConnected = (
- ConnectNamedPipe(pPipes[iIndex].hPipe, &(pPipes[iIndex].o)) ||
- GetLastError() == ERROR_PIPE_CONNECTED
- );
- // если операция "успела" выполниться –
- // выставим соответствующее событие
- if (bConnected) SetEvent(pEvents[iIndex]);
- }
- int main(int argc, char* argv[])
- {
- //...
- // создадим PIPE_INSTANCES экземпляров канала
- for (int i = 0; i < PIPE_INSTANCES; i++)
- {
- pPipes[i].bConnected = FALSE;
- pEvents[i] = pPipes[i].o.hEvent = CreateEvent(NULL,true,false,NULL);
- pPipes[i].hPipe = CreateNamedPipe(NamePipe,PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED,PIPE_TYPE_MESSAGE,PIPE_INSTANCES,PipeSize,PipeSize,0,NULL);
- // обработка ошибки
- if (pPipes[i].hPipe == INVALID_HANDLE_VALUE) return -1;
- // инициировать подключение
- ReconnectPipe(i);
- }
- // бесконечный цикл обработки подключений клиентов
- DWORD dwBytesRead;
- DWORD dwPipeIndex;
- BOOL bResult;
- while (1)
- {
- // ждем завершения операции ввода-вывода
- dwPipeIndex = WaitForMultipleObjects(PIPE_INSTANCES, pEvents,
- FALSE, INFINITE) - WAIT_OBJECT_0;
- if (dwPipeIndex < 0 || dwPipeIndex >= PIPE_INSTANCES)
- {
- cout << "Error! THIS IS ERROR";
- }
- else
- {
- // если еще не подключен
- if (!pPipes[dwPipeIndex].bConnected)
- {
- cout << dwPipeIndex << " Connect";
- pPipes[dwPipeIndex].bConnected = TRUE;
- }
- else
- {
- // получим результат чтения данных
- bResult = GetOverlappedResult(
- pPipes[dwPipeIndex].hPipe,
- &pPipes[dwPipeIndex].o,
- &dwBytesRead,
- FALSE);
- if (bResult)
- {
- cout << dwPipeIndex <<") " << pPipes[dwPipeIndex].buf << endl;
- }
- else
- {
- cout << dwPipeIndex << " disconnect";
- ReconnectPipe(dwPipeIndex);
- continue;
- }
- }
- // запускаем чтение/запись данных
- while (ReadFile(
- pPipes[dwPipeIndex].hPipe,
- pPipes[dwPipeIndex].buf, BUFFER_SIZE,
- &dwBytesRead,
- &pPipes[dwPipeIndex].o)
- // или WriteFile(...)
- )
- {
- cout << dwPipeIndex <<") " << pPipes[dwPipeIndex].buf;
- }
- // ошибка?
- if (GetLastError() != ERROR_IO_PENDING)
- {
- cout << dwPipeIndex << " disconnect";
- ReconnectPipe(dwPipeIndex);
- continue;
- }
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment