1

I'm trying to establish a named pipe (2 way) between a python 2.7 and a C# application. It works fine for byte mode, but when I'm change to message mode in the python server side the C# client claims it's still byte mode.

Here is my python code:

import win32pipe, win32file

p = win32pipe.CreateNamedPipe("\\\\.\\pipe\\test_pipe",
    win32pipe.PIPE_ACCESS_DUPLEX,
    win32pipe.PIPE_TYPE_MESSAGE|win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT,
    1, 65536, 65536,300,None)

print("Waiting for connection");
win32pipe.ConnectNamedPipe(p, None)
print("Client has connected")
win32file.WriteFile(p, "TestMessage".encode('utf-8'))
p.close()

My C# -Code:

class Program
{
    static void Main(string[] args)
    {
        using (NamedPipeClientStream clientStream = new NamedPipeClientStream(".", "test_pipe", PipeDirection.InOut))
        {
            clientStream.Connect();
            Console.WriteLine("Connected");
            string inMessage = ProcessSingleReceivedMessage(clientStream);
            Console.WriteLine("in Message " + inMessage);
        }
        Console.ReadLine();
    }


    private static string ProcessSingleReceivedMessage(NamedPipeClientStream namedPipeClient)
    {
        Console.WriteLine("Transmission mode: " + namedPipeClient.TransmissionMode);
        StringBuilder messageBuilder = new StringBuilder();
        string messageChunk = string.Empty;
        byte[] messageBuffer = new byte[5];
        do
        {
            namedPipeClient.Read(messageBuffer, 0, messageBuffer.Length);
            messageChunk = Encoding.UTF8.GetString(messageBuffer);
            messageBuilder.Append(messageChunk);
            messageBuffer = new byte[messageBuffer.Length];
        }
        while (!namedPipeClient.IsMessageComplete);
        return messageBuilder.ToString();
    }}

For simplification I've only posted the transmission from python to C#, because here the error appears here. The c# client for some reason thinks the transmission is Byte, hence an InvalidOperationException occurs saying "ReadMode is not PipeTransmissionMode.Message." What did I do wrong.

1 Answer 1

2

With named pipes, both the client and the server have to individually set up the read mode of their side of the pipe. Simply setting one side to message mode is not sufficient. Add this line below clientStream.Connect(); in your C#.

clientStream.ReadMode = PipeTransmissionMode.Message;

For more information, see the following:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.