Python与C#hangs之间的命名管道双工通信

2024-09-30 01:29:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在python(管道服务器)和C#(管道客户端)之间实现一个命名的管道双工通信。如果管道服务器从管道中读取数据,然后向管道中写入数据,而管道客户端则相反,那么它就工作了。但是,当我更改顺序,使管道服务器先写后读,管道客户机反之亦然时,程序在读取时挂起(ReadLine()),没有任何错误或异常。我实现了异常处理,但是为了更好的概述,这里省略了它。你知道吗

以下代码正常工作:

# Python 2 pipe server (ReadThenWrite)
pipe_handle = win32pipe.CreateNamedPipe(pipeName, win32pipe.PIPE_ACCESS_DUPLEX, ...)
win32pipe.ConnectNamedPipe(pipe_handle, None)

(_, read_message) = win32file.ReadFile(pipe_handle, 1000)
print('Received: ' + read_message)

win32file.WriteFile(pipe_handle, 'server')

win32file.FlushFileBuffers(pipe_handle)
win32pipe.DisconnectNamedPipe(pipe_handle)
win32file.CloseHandle(pipe_handle)
// C# pipe client (WriteThenRead)
NamedPipeClientStream pipeClient = NamedPipeClientStream(".", pipeName, PipeDirection.InOut)
pipeClient.Connect();

StreamWriter sw = new StreamWriter(pipeClient);
sw.AutoFlush = true;
sw.WriteLine("client");

StreamReader sr = new StreamReader(pipeClient);
string temp = sr.ReadLine();
Console.WriteLine("Received: " + temp);

在下面的代码中,只有读和写的顺序被交换,其他的都没有改变。奇怪的是,C应用程序在阅读时挂起。你知道吗

# Python 2 pipe server (WriteThenRead)
pipe_handle = win32pipe.CreateNamedPipe(pipeName, win32pipe.PIPE_ACCESS_DUPLEX, ...)
win32pipe.ConnectNamedPipe(pipe_handle, None)

win32file.WriteFile(pipe_handle, 'server')

(_, read_message) = win32file.ReadFile(pipe_handle, 1000)
print('Received: ' + read_message)

win32file.FlushFileBuffers(pipe_handle)
win32pipe.DisconnectNamedPipe(pipe_handle)
win32file.CloseHandle(pipe_handle)
// C# pipe client (ReadThenWrite)
NamedPipeClientStream pipeClient = NamedPipeClientStream(".", pipeName, PipeDirection.InOut)
pipeClient.Connect();

StreamReader sr = new StreamReader(pipeClient);
string temp = sr.ReadLine(); // here it hangs
Console.WriteLine("Received: " + temp);

StreamWriter sw = new StreamWriter(pipeClient);
sw.AutoFlush = true;
sw.WriteLine("client");

如果在管道服务器(WriteThenRead)中删除了管道读取,则管道客户端不会挂起并读取消息。你知道吗

作为一种解决方法,管道服务器在写入(resp。在读取之前),管道客户端在写入之前再次连接到它(resp。阅读后)。但它不被用作双相管。你知道吗

为什么会发生这种行为?这个问题怎么解决?你知道吗

任何帮助都将不胜感激,谢谢!你知道吗


Tags: 服务器client客户端messageread管道serversw

热门问题