编程语言
首页 > 编程语言> > C#异步命名管道永远等待

C#异步命名管道永远等待

作者:互联网

我正在使用异步管道,并且在某些时候服务器和客户端都互相等待,却什么也不做.这是我的代码:

服务器:

var buffer = new byte[BufferSize];
using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
{
    // Wait for client.
    Logger.Trace("Waiting for connection ...");
    var asyncResult = server.BeginWaitForConnection(a => { }, null);
     while (true)
     {
          await Task.Delay(MillisecondsDelay);
          if (asyncResult.IsCompleted) break;
      }
      server.EndWaitForConnection(asyncResult);
      Logger.Trace("Connection established.");


       using (var sr = new StreamReader(server))
       using (var sw = new StreamWriter(server))
       {
             // Send work.
             Logger.Trace("Sending operations...");
             await sw.WriteAsync(JsonConvert.SerializeObject(data));
             await sw.FlushAsync();
             server.WaitForPipeDrain();

              // Wait for response.
              var bytesRead = await server.ReadAsync(buffer, 0, buffer.Length);

       .....

客户:

        // Read data from the pipe...
 using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous))
 {
      Logger.Trace("Connecting to server...");
      client.Connect();
      Logger.Trace("Connected.");

      using (var sr = new StreamReader(client))
      using (var sw = new StreamWriter(client))
      {
           // Read operations.
           Logger.Trace("Waiting operations...");
           var text = await sr.ReadToEndAsync();
       .....

我的日志是:

2016-10-04 16:09:51.5375 => (TRACE) | MyController.Execute : Waiting for connection ... |  
2016-10-04 16:09:52.0706 => (TRACE) | MyController+<Execute>d__5.MoveNext : Connection established. |  
2016-10-04 16:09:52.0706 => (TRACE) | MyController+<Execute>d__5.MoveNext : Sending operations... |  

和:

2016-10-04 16:09:51.8486 => (TRACE) | EXE.Program.Process : Connecting to server... | 
2016-10-04 16:09:51.8696 => (TRACE) | EXE.Program.Process : Connected. | 
2016-10-04 16:09:51.8696 => (TRACE) | EXE.Program.Process : Waiting operations... | 

然后什么都没有!

之后,它似乎陷入僵局.

我认为我应该在服务器或客户端每次写入之后使用WaitForPipeDrain(),但是这样做似乎没有帮助.

客户端读取操作永不返回.

有任何想法吗?

解决方法:

我认为问题出在ReadToEndAsync方法中. StreamReader无法确定传输已结束.例如,连接速度可能很慢,仅发送了一半的数据.通常,在这些情况下,您需要提出自己的“协议”来发送数据.有多种方法,这里有几个:

>等待终止符.很多次,我都看到ASCII字符4表示“ EOT”(end of transmission).但是,这是基于这样的假设,即您的消息不仅是二进制数据流,还可能包含该字符.您可以将终止符设置为序列,而几乎不会出现在流中的几个字符.
>在消息前加上要发送的数据长度.例如,前4个字节始终是长度,抓住它后,您现在知道要读取多少.

标签:asynchronous,named-pipes,c
来源: https://codeday.me/bug/20191026/1938009.html