【问题标题】:NamedPipeServerStream receive MAX=1024 bytes, why?NamedPipeServerStream 接收 MAX=1024 字节,为什么?
【发布时间】:2015-08-11 07:51:07
【问题描述】:

我正在使用 NamedPipeStream,客户端和服务器,我正在从客户端向服务器发送数据,数据是包含二进制数据的序列化对象。

当服务器端接收数据时,它总是有 MAX 1024 大小,而客户端发送更多!所以当尝试序列化数据时,这会导致以下异常: “未终止的字符串。预期的分隔符:”。路径‘数据’,第 1 行,位置 1024。”

服务器缓冲区大小定义为:

protected const int BUFFER_SIZE = 4096*4;
var stream = new NamedPipeServerStream(PipeName,
                                                   PipeDirection.InOut,
                                                   1,
                                                   PipeTransmissionMode.Message,
                                                   PipeOptions.Asynchronous,
                                                   BUFFER_SIZE,
                                                   BUFFER_SIZE,
                                                   pipeSecurity);


        stream.ReadMode = PipeTransmissionMode.Message;

我正在使用:

    /// <summary>
    /// StreamWriter for writing messages to the pipe.
    /// </summary>
    protected StreamWriter PipeWriter { get; set; }

读取函数:

/// <summary>
/// Reads a message from the pipe.
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
protected static byte[] ReadMessage(PipeStream stream)
{
    MemoryStream memoryStream = new MemoryStream();

    byte[] buffer = new byte[BUFFER_SIZE];

    try
    {
        do
        {
            if (stream != null)
            {
                memoryStream.Write(buffer, 0, stream.Read(buffer, 0, buffer.Length));
            }

        } while ((m_stopRequested != false) && (stream != null) && (stream.IsMessageComplete == false));
    }
    catch
    {
        return null;
    }
    return memoryStream.ToArray();
}


protected override void ReadFromPipe(object state)
{
    //int i = 0;
    try
    {
        while (Pipe != null && m_stopRequested == false)
        {
            PipeConnectedSignal.Reset();

            if (Pipe.IsConnected == false)
            {//Pipe.WaitForConnection();
                var asyncResult = Pipe.BeginWaitForConnection(PipeConnected, this);

                if (asyncResult.AsyncWaitHandle.WaitOne(5000))
                {
                    if (Pipe != null)
                    {
                        Pipe.EndWaitForConnection(asyncResult);
                        // ...
                        //success;
                    }
                }
                else
                {
                    continue;
                }
            }
            if (Pipe != null && Pipe.CanRead)
            {
                byte[] msg = ReadMessage(Pipe);

                if (msg != null)
                {
                    ThrowOnReceivedMessage(msg);
                }
            }
        }
    }
    catch (System.Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(" PipeName.ReadFromPipe Ex:" + ex.Message);
    }
}

我在客户端看不到可以定义或更改缓冲区大小的地方!

有什么想法吗?!

【问题讨论】:

  • 缓冲区大小并不重要 - 您正在处理 数据。你是如何处理序列化和反序列化的?
  • 客户端代码是什么样的?
  • @Luaan:消息模式有点特别。来自 MSDN 的配额:“管道将每次写入操作期间写入的字节视为消息单元”
  • @Luaan:谢谢,你刚刚在我的代码中发现了一个错误 :)
  • @Joseph 你从来没有说过你在使用StreamWriter,这正是我们从一开始就要求提供的信息。这其实是你的问题!它将发出几个单独的Writes,这将产生单独的消息。

标签: c# namedpipeserverstream


【解决方案1】:

基本问题是您没有阅读足够的内容。如果PipeStream.IsMessageComplete 为假,您需要重复读取操作,并继续这样做直到它返回真 - 这告诉您整个消息已被阅读。根据您的反序列化器,您可能需要将数据存储在自己的缓冲区中,或者创建一些包装流来为您处理。

一个简单的例子说明这如何用于简单的字符串反序列化:

void Main()
{
  var serverTask = Task.Run(() => Server()); // Just to keep this simple and stupid

  using (var client = new NamedPipeClientStream(".", "Pipe", PipeDirection.InOut))
  {
    client.Connect();
    client.ReadMode = PipeTransmissionMode.Message;

    var buffer = new byte[1024];
    var sb = new StringBuilder();

    int read;
    // Reading the stream as usual, but only the first message
    while ((read = client.Read(buffer, 0, buffer.Length)) > 0 && !client.IsMessageComplete)
    {
      sb.Append(Encoding.ASCII.GetString(buffer, 0, read));
    }

    Console.WriteLine(sb.ToString());
  }
}

void Server()
{
  using (var server
    = new NamedPipeServerStream("Pipe", PipeDirection.InOut, 1, 
                                PipeTransmissionMode.Message, PipeOptions.Asynchronous)) 
  {
    server.ReadMode = PipeTransmissionMode.Message;      
    server.WaitForConnection();

    // On the server side, we need to send it all as one byte[]
    var buffer = Encoding.ASCII.GetBytes(File.ReadAllText(@"D:\Data.txt"));
    server.Write(buffer, 0, buffer.Length); 
  }
}

顺便说一句 - 我可以轻松地一次读取或写入任意数量的数据 - 限制因素是 使用的缓冲区,而不是管道使用的缓冲区;虽然我使用的是本地命名管道,但对于 TCP 管道来说可能会有所不同(虽然它会有点烦人 - 它应该从你那里抽象出来)。

编辑:

好的,现在终于明白你的问题是什么了。您不能使用StreamWriter - 当发送消息足够长时,将导致管道流上的多个Write 调用,从而为您的数据生成多个单独的消息。如果您希望将整个消息作为单个消息,则必须使用单个 Write 调用。例如:

var data = Encoding.ASCII.GetBytes(yourJsonString);
Write(data, 0, data.Length);

1024 长的缓冲区是StreamWriters,它与命名管道无关。在任何网络场景中使用StreamWriter/StreamReader 都是一个坏主意,即使在使用原始 TCP 流时也是如此。这不是它的设计目的。

【讨论】:

  • 服务器这样做,它在循环中:while ( (stream != null) && (stream.IsMessageComplete == false));
  • @Joseph stream != null 似乎没有必要。无论如何,您可以只发布您的“读取流并调用反序列化器”代码吗?这可能是问题所在。
  • @Joseph 我很确定问题出在 发送 端,而不是接收端。我的答案已经说明了我认为问题出在哪里以及如何解决,你不能试试吗?接收端仍然有奇怪的东西(你为什么一直检查流是否为 null?它不能 变成 null。为什么你使用异步连接只是为了同步等待它? ),但没有什么破坏游戏的。
  • 现在我看到了你的更新,现在它似乎是我问题的答案,我会修复我的问题并更新(标记为答案)结果!
猜你喜欢
  • 2014-09-20
  • 2019-06-06
  • 2015-07-01
  • 2014-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-27
  • 2016-03-02
相关资源
最近更新 更多