我想通過管道將數據從c#應用程序發送到C++應用程序。 這裏是我做了什麼:通過管道在C++和c#之間進行通信
這是C++客戶端:
#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\\BvrPipe", 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
{
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");
}
CloseHandle(hFile);
}
return 0;
}
,這裏的C#服務器
using System;
using System.IO;
using System.IO.Pipes;
using System.Threading;
namespace PipeApplication1{
class ProgramPipeTest
{
public void ThreadStartServer()
{
// Create a name pipe
using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("\\\\.\\pipe\\BvrPipe"))
{
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");
}
static void Main(string[] args)
{
ProgramPipeTest Server = new ProgramPipeTest();
Thread ServerThread = new Thread(Server.ThreadStartServer);
ServerThread.Start();
}
}
}
當我啓動服務器,然後來自客戶端的客戶端GetLastErrror返回2(系統可以沒有找到指定的文件。)
對此有任何想法。 謝謝
我可以證實這一點,我已經使用C#和C++之間的管道,我做了在創建NamedPipeServerStream時不在管道名稱上使用Pipe \ prefix – 2016-10-05 10:52:03
在上面的代碼中,直到我們從C++代碼調用管道句柄上的CloseHandle,數據不會傳遞到C#服務器。我也嘗試過「FlushFileBuffers」函數,它的功能 – 2017-02-27 05:23:43
@Raveendra你無法刷新套接字,請參閱http://stackoverflow.com/questions/12814835/flush-a-socket-in-c瞭解詳情。 ://www.tangentsoft.net/wskfaq/intermediate.html#packetscheme。 – 2017-02-28 11:32:15