2014-06-23 122 views
-1

我試圖在C#(服務器)和C++(客戶端)之間發送數據。現在我只能在它們之間成功發送一個數據。我如何從C#異步(實時)向C++發送多個值?C#和C++之間的異步管道

C#服務器

using (NamedPipeServerStream PServer1 = 
      new NamedPipeServerStream("MyNamedPipe", PipeDirection.InOut)) 
     { 
      Console.WriteLine("Server created"); 
      Console.WriteLine("Waiting for client connection..."); 
      PServer1.WaitForConnection(); 

      Console.WriteLine("Client conencted"); 

      try 
      { 
       // Read user input and send that to the client process. 
       using (StreamWriter sw = new StreamWriter(PServer1)) 
       { 
        sw.AutoFlush = true; 
        Console.Write("Enter text: "); 
        sw.WriteLine(Console.ReadLine()); 
       } 

      } 
      // Catch the IOException that is raised if the pipe is broken 
      // or disconnected. 
      catch (IOException e) 
      { 
       Console.WriteLine("ERROR: {0}", e.Message); 
      } 
      //PServer1.Close(); 
     } 

C++客戶

HANDLE hPipe; 

//Connect to the server pipe using CreateFile() 
hPipe = CreateFile( 
    g_szPipeName, // pipe name 
    GENERIC_READ | // read and write access 
    GENERIC_WRITE, 
    0,    // no sharing 
    NULL,   // default security attributes 
    OPEN_EXISTING, // opens existing pipe 
    0,    // default attributes 
    NULL);   // no template file 

if (INVALID_HANDLE_VALUE == hPipe) 
{ 
    printf("\nError occurred while connecting" 
     " to the server: %d", GetLastError()); 
    return 1; //Error 
} 
else 
{ 
    printf("\nCreateFile() was successful."); 
} 

//Read server response 
char szBuffer[BUFFER_SIZE]; 
DWORD cbBytes; 
BOOL bResult = ReadFile( 
    hPipe,    // handle to pipe 
    szBuffer,    // buffer to receive data 
    sizeof(szBuffer),  // size of buffer 
    &cbBytes,    // number of bytes read 
    NULL);    // not overlapped I/O 

if ((!bResult) || (0 == cbBytes)) 
{ 
    printf("\nError occurred while reading" 
     " from the server: %d", GetLastError()); 
    CloseHandle(hPipe); 
    return 1; //Error 
} 
else 
{ 
    printf("\nReadFile() was successful."); 
} 

printf("\nServer sent the following message: %s", szBuffer); 

//CloseHandle(hPipe); 
+1

認沽發送/在一個循環中接收代碼? – stijn

+0

嘗試過,但未按預期工作 – Neno0o

+1

然後將此信息添加到您的問題中,並指定「沒有工作」意味着*確切地說* – stijn

回答

0

如果要發送多條消息,則必須安裝在客戶端和服務器的循環。

此外,請注意,由於using聲明,管道的Dispose()方法正在被調用,因此關閉它。所以你必須有using塊內的循環。

因此,像:

(服務器端)

using(var sw = new StreamWriter(PServer1)) 
{ 
    sw.AutoFlush = true; 

    while(Condition) // This could be done by analyzing the user's input and looking for something special... 
    { 
    Console.Write("Enter text: "); 
    sw.WriteLine(Console.ReadLine()); 
    } 
} 
+0

我在兩個循環中,似乎在服務器上正常工作,但在客戶端無法正常工作。例如:在服務器「x」上,在客戶端「x」「x」「x」上的3的循環。無法將服務器的第一個循環與客戶端配對。有什麼建議麼? – Neno0o