gpt4 book ai didi

c# - 带 c# 服务器的命名管道客户端 (c++)

转载 作者:可可西里 更新时间:2023-11-01 11:49:41 31 4
gpt4 key购买 nike

我想要做的是拥有一个用 C++ 编写的命名管道客户端,以便能够与用 C# 编写的命名管道服务器进行通信。到目前为止,我一直无法做到这一点。

CreateFile 给我一个无效的句柄值,GetLastError 返回 2。

这是c++部分(客户端)

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <iostream>

using namespace std;

#define PIPE_NAME L"\\\\.\\pipe\\TestPipe"
#define BUFF_SIZE 512

int main()
{
HANDLE hPipe;

hPipe = CreateFile(PIPE_NAME, GENERIC_READ, 0, nullptr, OPEN_EXISTING, 0, nullptr);

if (hPipe == INVALID_HANDLE_VALUE)
{
cout << "INVALID_HANDLE_VALUE" << GetLastError() << endl;
cin.get();
return -1;
}

cout << hPipe << endl;

DWORD mode = PIPE_READMODE_MESSAGE;

SetNamedPipeHandleState(hPipe, &mode, nullptr, nullptr);

bool success = false;
DWORD read;

while(true)
{
TCHAR chBuff[BUFF_SIZE];
do
{
success = ReadFile(hPipe, chBuff, BUFF_SIZE*sizeof(TCHAR), &read, nullptr);
} while (!success);

_tprintf(TEXT("\"%s\"\n"), chBuff);
}
}

这是服务器

using System;
using System.IO.Pipes;
using System.Text;

namespace BasicServer
{

public static class Program
{
private static NamedPipeServerStream _server;

static void Main(string[] args)
{
_server = new NamedPipeServerStream(@"\\.\pipe\TestPipe", PipeDirection.Out, 1, PipeTransmissionMode.Message);
_server.WaitForConnection();
Console.WriteLine(_server.IsConnected);
Console.WriteLine("Client connected\n Sending message");
byte[] buff = Encoding.UTF8.GetBytes("Test message");
_server.Write(buff, 0, buff.Length);
while (true)
{
Console.ReadKey();
Console.Write("\b \b");
}
}
}
}

我已经能够与用 C# 编写的客户端连接,但据我所知,c++ -> C# 通信应该是可能的。

这是我用 C# 编写的测试客户端,它可以工作

using System;
using System.IO.Pipes;
using System.Text;

namespace BasicClientC
{

public class Program
{
private static NamedPipeClientStream client;

static void Main(string[] args)
{
client = new NamedPipeClientStream(@".", @"\\.\pipe\TestPipe", PipeDirection.In);
client.Connect();
byte[] buffer = new byte[512];
client.Read(buffer, 0, 512);
Console.WriteLine(Encoding.UTF8.GetString(buffer));
Console.ReadKey();
}
}
}

那么我的错误在哪里呢?

最佳答案

我知道为什么。

  1. 在 C# 中创建管道时,仅使用 "TestPipe" 作为管道名称,不要将 \\.\pipe\ 包含为此管道名称的前缀。

  2. 在 C++ 中,使用管道的完整路径:"\\.\pipe\TestPipe"。您的 C++ 逻辑不需要为此进行更改,因为您已经很好地定义了它:L"\\\\.\\pipe\\TestPipe"

This may help, as well .有趣的是,我在三年多前遇到过这个问题,现在我又想起来了。

关于c# - 带 c# 服务器的命名管道客户端 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33133993/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com