Reputation: 28510
I have a named pipe server. The client sends the message, which seems OK, however the server just hangs on the line var stringData = textReader.ReadToEnd();
.
var namedPipeServerStream = new NamedPipeServerStream(_pipeName,
PipeDirection.In,
1,
PipeTransmissionMode.Byte,
PipeOptions.Asynchronous);
namedPipeServerStream.WaitForConnection();
using (var textReader = new StreamReader(namedPipeServerStream))
{
var stringData = textReader.ReadToEnd();
_callback(stringData);
namedPipeServerStream.Flush();
namedPipeServerStream.Close();
}
Thread.Sleep(1);
The client looks like so:
public void Send(string message)
{
var pipeStream = new NamedPipeClientStream(_serverName,
_pipeName,
PipeDirection.Out,
PipeOptions.Asynchronous);
pipeStream.Connect(_timeout);
var buffer = UTF8.GetBytes(message);
pipeStream.Write(buffer, 0, buffer.Length);
}
Why is this hanging?
Upvotes: 1
Views: 3754
Reputation: 351
I got the same problem, and I fixed it with flush on the WRITE side.
Flush pipe on client side right after stream writing so that the server side can get the message.
Upvotes: 2
Reputation: 24410
NamedPipe streams, like network streams, have no definite end, they just temporarily "dry up", that's why your ReadToEnd
call indefinitely tries to read more data.
However, you could change the PipeTransmissionMode
to Message
on the server-side to make each write to the pipe to be treated as a separate message, and then read from the stream until IsMessageComplete
returns true
. e.g.:
using (var namedPipeServerStream = new NamedPipeServerStream(_pipeName,
PipeDirection.InOut,
1,
PipeTransmissionMode.Message,
PipeOptions.Asynchronous))
{
namedPipeServerStream.WaitForConnection();
MemoryStream ms = new MemoryStream();
byte[] buffer = new byte[0x1000];
do { ms.Write(buffer, 0, namedPipeServerStream.Read(buffer, 0, buffer.Length)); }
while (!namedPipeServerStream.IsMessageComplete);
string stringData = Encoding.UTF8.GetString(ms.ToArray());
_callback(stringData);
}
Thread.Sleep(1);
Upvotes: 3