I am implementing a named pipe duplex communication between python (pipe server) and C# (pipe client). If the pipe server reads from pipe and then writes to it and the pipe client does so vice versa, it works. However, when I change the order so that pipe server writes then reads and the pipe client does so vice versa, the program hangs at reading (ReadLine()) without any error or exception. I implement exception handling, but omit it here in favour of a better overview.
What I have tried:
c# Code
using (NamedPipeClientStream pipeClient =
new NamedPipeClientStream(".", "CSServer", PipeDirection.InOut))
{
Console.Write("Attempting to connect to pipe...");
pipeClient.Connect();
Console.WriteLine("Connected to pipe.");
Console.WriteLine("There are currently {0} pipe server instances open.",
pipeClient.NumberOfServerInstances);
StreamWriter sw = new StreamWriter(pipeClient);
StreamReader sr = new StreamReader(pipeClient);
while (true)
{
try
{
sw.AutoFlush = true;
sw.WriteLine("Hello from c#");
string temp = sr.ReadLine();
Console.WriteLine("Received from python : {0}", temp);
Console.ReadLine();
}
catch (EndOfStreamException)
{
break;
}
}
}
}
python Code
import win32file
import win32pipe
import time
# Python 2 pipe server (ReadThenWrite)
pipeName="CSServer"
pipe_handle = win32pipe.CreateNamedPipe(
r'\\.\pipe\\'+pipeName,
win32pipe.PIPE_ACCESS_DUPLEX,
win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT,
1, 65536, 65536,
0,
None)
win32pipe.ConnectNamedPipe(pipe_handle, None)
while True:
(_, read_message) = win32file.ReadFile(pipe_handle, 1000)
print('Received from c#: ' + read_message.decode('utf-8'))
win32file.WriteFile(pipe_handle, 'Hello from Python'.encode())
win32file.FlushFileBuffers(pipe_handle)
# win32pipe.DisconnectNamedPipe(pipe_handle)
#win32file.CloseHandle(pipe_handle)
time.sleep(2)
I am able read the in python console but not in c# console file
i need to read and write the data within 2 sec of time
please help me any mistake i have did in my code