Roel
Roel

Reputation: 764

Named pipe communication between C# server and C++ client

I have a C# server and a C++ client. The C# server works just fine as I tested it with a C# client and all the messages from the client were properly transferred to the server. However, when implementing the C++ client, I seem to run into certain issues.

First of all, this is my C# server:

    Task.Factory.StartNew(() =>
                {
                    NamedPipeServerStream server = new NamedPipeServerStream(name);
                    server.WaitForConnection();

                    StreamReader reader = new StreamReader(server);

                    Console.WriteLine("Client connected");

                    while (true)
                    {
                        if (reader.ReadLine() != null)
                            Console.WriteLine(reader.ReadLine());
                    }
                });

The name variable is passed as a parameter to the method. My C++ code is the following:

HANDLE hPipe;
    DWORD dwWritten;

    hPipe = CreateFile(TEXT("\\\\.\\pipe\\testpipe"),
        GENERIC_READ | GENERIC_WRITE,
        0,
        NULL,
        OPEN_EXISTING,
        0,
        NULL);
    if (hPipe != INVALID_HANDLE_VALUE)
    {
        WriteFile(hPipe,
            "Hello Pipe\n",
            12,   // = length of string + terminating '\0' !!!
            &dwWritten,
            NULL);

        CloseHandle(hPipe);
    }

The server's output is the following:

[PIPE] Client connected
[PIPE] 

Anyone got any suggestion? Perhaps I am going by this all wrong, as I am totally new at pipes.

Thanks in advance.

Upvotes: 1

Views: 1286

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70701

It's hard to diagnose code, especially network code, without a good Minimal, Complete, and Verifiable example that reliably reproduces the problem. But your server's C# code does have at least one glaring problem:

while (true)
{
    if (reader.ReadLine() != null)
        Console.WriteLine(reader.ReadLine());
}

Here, you first read a line from the stream, and then if it's not null, you read another line and display that. This means you are discarding every other line being sent.

The loop should probably look more like this:

string line;

while ((line = reader.ReadLine()) != null)
{
    Console.WriteLine(line);
}

I don't understand how your C# client worked. Maybe it was incorrectly implemented as well, preceding the desired lines with blank lines to balance out the bug in the server code.

Upvotes: 1

Related Questions