Search code examples
c#c++named-pipes

Pipe not reading data correctly


C++ side

hPipe = CreateFile(TEXT((LPTSTR)"\\\\.\\pipe\\PIPENAME"), GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
char buf[100];
DWORD cbWritten;

if ((hPipe == NULL || hPipe == INVALID_HANDLE_VALUE))
{
    printf("Could not open the pipe  - (error %d)\n", GetLastError());

}
else
{
    do
    {
        printf("Enter your message: ");
        scanf_s("%s", buf);
        WriteFile(hPipe, buf, (DWORD)strlen(buf), &cbWritten, NULL);
        memset(buf, 0xCC, 100);


    } while (true);
}
memset(buf, 0xCC, 100);

Now that's the side I'm trying to send data to my c# program here is the c# code

 using (var pipeServer = new NamedPipeServerStream("PIPENAME", PipeDirection.InOut))
        {
            using (var reader = new StreamReader(pipeServer))
            {
                using (var writer = new StreamWriter(pipeServer))
                {
                    var running = true;
                    MessageBox.Show("Server is waiting for a client");
                    pipeServer.WaitForConnection();
                    MessageBox.Show("Server: Prompting for Input");
                    writer.Flush();
                    while (running)
                    {
                        //pipeServer.WaitForPipeDrain();
                        var message = reader.ReadToEnd();
                        MessageBox.Show("Received message: " + message);
                        if (message.Equals("quit"))
                        {
                            writer.WriteLine("quit");
                            running = false;
                        }
                    }
                }
            }
        }
        Console.WriteLine("Server Quits");

I've tried using ReadLine also but it keeps reading till I close the c++ pipe side

Basically I'm trying to send a message from the C++ side for example "Message1" and the c# side has to read it.

but atm when I send the message "Message1" nothing happens and if I then send "Message2" nothing happens either. but if I close the program ( cpp side ) it'll receive "Message1Message2"


Solution

  • ReadLine() is looking for an end-of-line character sequence, or the end of stream, before it returns.

    When your C++ code exits, the pipe closes and thus you see ReadLine return. But for the individual messages, you are not sending an end-of-line sequence.

    Reference the s type specifier for the scanf() family of functions:

    String, up to first white-space character (space, tab or newline).

    Ie. any input end-of-line is not included in the data you send.