C ++ / C#:管道WriteFile()在关闭管道句柄之前不会将数据写入接收器端

时间:2017-02-27 11:28:33

标签: c# c++ pipe named-pipes language-interoperability

我正在尝试使用stringNamed Pipe数据从C ++模块写入C#模块。

我的代码如下:

C#(管道服务器):

namespace CSPipe
{
    class Program
    {
        public void ThreadStartServer()
        {
            // Create a name pipe
            using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("samplePipe"))
            {
                Console.WriteLine("[Server] Pipe created {0}", pipeStream.GetHashCode());

                // Wait for a connection
                pipeStream.WaitForConnection();
                Console.WriteLine("[Server] Pipe connection established");

                using (StreamReader sr = new StreamReader(pipeStream))
                {
                    string temp;
                    // We read a line from the pipe and print it together with the current time
                    while ((temp = sr.ReadLine()) != null)
                    {
                        Console.WriteLine("{0}: {1}", DateTime.Now, temp);
                    }
                }
            }

            Console.WriteLine("Connection lost");
            Console.ReadKey();
        }

        static void Main(string[] args)
        {
            Program Server = new Program();

            Thread ServerThread = new Thread(Server.ThreadStartServer);

            ServerThread.Start();

        }

    }

}

C ++(Pipe Client):

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>



int _tmain(int argc, _TCHAR* argv[])
{
      HANDLE hFile;
      BOOL flg;
      DWORD dwWrite;
      char szPipeUpdate[200];
      hFile = CreateFile(L"\\\\.\\pipe\\samplePipe", GENERIC_WRITE,
                                 0, NULL, OPEN_EXISTING,
                                  0, NULL);

      strcpy(szPipeUpdate,"Data from Named Pipe client for createnamedpipe");
      if(hFile == INVALID_HANDLE_VALUE)
      { 
          DWORD dw = GetLastError();
          printf("CreateFile failed for Named Pipe client\n:" );
      }
      else
      {
          while(1) 
          {
          flg = WriteFile(hFile, szPipeUpdate, strlen(szPipeUpdate),            &dwWrite, NULL);

          if (FALSE == flg)
          {
             printf("WriteFile failed for Named Pipe client\n");
          }
          else
          {
             printf("WriteFile succeeded for Named Pipe client\n");
          }
           FlushFileBuffers(hFile);
          // CloseHandle(hFile);
          }

      }
      getchar();
    return 0;
}

WriteFile()立即返回,但C#服务器没有获取任何写入的管道数据。如果我在C ++代码中取消注释CloseHandle(),那么C#Server将获取管道数据。每次我将数据写入管道时,我都不想关闭和打开管道。有没有什么方法可以只打开一次管道,并且每当我必须将数据写入管道时执行WriteFile()

0 个答案:

没有答案