xnim

Untitled

Nov 18th, 2012
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 3.61 KB | None | 0 0
  1. #include <Windows.h>
  2. #include <iostream>
  3. #include <string>
  4. using namespace std;
  5. #define BUFFER_SIZE 256
  6. #define PipeSize 256
  7. #define PIPE_INSTANCES 10
  8. #define  NamePipe  "\\\\.\\pipe\\pipe"
  9. #define NameEvent "pipeEvent"
  10. // структура-описатель одного подключения
  11. struct PIPE_INFO
  12. {
  13.     HANDLE hPipe;
  14.     OVERLAPPED o;
  15.     BOOL bConnected;
  16.     char buf[BUFFER_SIZE];
  17. };
  18.  
  19. // вектор подключений
  20. PIPE_INFO pPipes[PIPE_INSTANCES];
  21.  
  22. // вектор событий для мониторинга ввода-вывода
  23. HANDLE pEvents[PIPE_INSTANCES];
  24.  
  25. ///////////////////////////////////////////////////////
  26.  
  27. // функция переустановления соединения
  28. void ReconnectPipe(int iIndex)
  29. {
  30.     // если подключение осуществлено
  31.     if (pPipes[iIndex].bConnected)
  32.     {
  33.         // закрытие соединения
  34.         pPipes[iIndex].bConnected = FALSE;
  35.         DisconnectNamedPipe(pPipes[iIndex].hPipe);
  36.     }
  37.  
  38.     // инициализация нового соединения
  39.     BOOL bConnected = (
  40.         ConnectNamedPipe(pPipes[iIndex].hPipe, &(pPipes[iIndex].o)) ||
  41.         GetLastError() == ERROR_PIPE_CONNECTED
  42.         );
  43.  
  44.     // если операция "успела" выполниться –
  45.     // выставим соответствующее событие
  46.     if (bConnected) SetEvent(pEvents[iIndex]);
  47. }
  48.  
  49. int main(int argc, char* argv[])
  50. {
  51.     //...
  52.  
  53.         // создадим PIPE_INSTANCES экземпляров канала
  54.         for (int i = 0; i < PIPE_INSTANCES; i++)
  55.         {
  56.             pPipes[i].bConnected = FALSE;
  57.             pEvents[i] = pPipes[i].o.hEvent = CreateEvent(NULL,true,false,NULL);
  58.             pPipes[i].hPipe = CreateNamedPipe(NamePipe,PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED,PIPE_TYPE_MESSAGE,PIPE_INSTANCES,PipeSize,PipeSize,0,NULL);        
  59.  
  60.             // обработка ошибки
  61.             if (pPipes[i].hPipe == INVALID_HANDLE_VALUE) return -1;
  62.  
  63.             // инициировать подключение
  64.             ReconnectPipe(i);
  65.         }
  66.  
  67.         // бесконечный цикл обработки подключений клиентов
  68.         DWORD dwBytesRead;
  69.         DWORD dwPipeIndex;
  70.         BOOL bResult;
  71.         while (1)
  72.         {
  73.             // ждем завершения операции ввода-вывода
  74.             dwPipeIndex = WaitForMultipleObjects(PIPE_INSTANCES, pEvents,
  75.                 FALSE, INFINITE) - WAIT_OBJECT_0;
  76.  
  77.             if (dwPipeIndex < 0 || dwPipeIndex >= PIPE_INSTANCES)
  78.             {
  79.                 cout << "Error! THIS IS ERROR";
  80.             }
  81.             else
  82.             {
  83.                 // если еще не подключен
  84.                 if (!pPipes[dwPipeIndex].bConnected)
  85.                 {
  86.                     cout << dwPipeIndex << " Connect";
  87.                     pPipes[dwPipeIndex].bConnected = TRUE;
  88.                 }
  89.                 else
  90.                 {
  91.                     // получим результат чтения данных
  92.                     bResult = GetOverlappedResult(
  93.                         pPipes[dwPipeIndex].hPipe,
  94.                         &pPipes[dwPipeIndex].o,
  95.                         &dwBytesRead,
  96.                         FALSE);
  97.  
  98.                     if (bResult)
  99.                     {
  100.                         cout << dwPipeIndex <<") " << pPipes[dwPipeIndex].buf << endl;
  101.                     }
  102.                     else
  103.                     {
  104.                         cout << dwPipeIndex << " disconnect";
  105.                         ReconnectPipe(dwPipeIndex);
  106.                         continue;
  107.                     }
  108.                 }
  109.  
  110.                 // запускаем чтение/запись данных
  111.                 while (ReadFile(
  112.                     pPipes[dwPipeIndex].hPipe,
  113.                     pPipes[dwPipeIndex].buf, BUFFER_SIZE,
  114.                     &dwBytesRead,
  115.                     &pPipes[dwPipeIndex].o)
  116.                     // или WriteFile(...)
  117.                     )
  118.                 {
  119.                     cout << dwPipeIndex <<") " << pPipes[dwPipeIndex].buf;
  120.                 }
  121.  
  122.                 // ошибка?
  123.                 if (GetLastError() != ERROR_IO_PENDING)
  124.                 {
  125.                     cout << dwPipeIndex << " disconnect";
  126.                     ReconnectPipe(dwPipeIndex);
  127.                     continue;
  128.                 }
  129.             }
  130.         }
  131.  
  132.         return 0;
  133. }
Advertisement
Add Comment
Please, Sign In to add comment