4

クライアントとサーバーの NamedPipeStream を使用しています。クライアントからサーバーにデータを送信しています。データは、バイナリ データを含むシリアル化オブジェクトです。

サーバー側がデータを受信すると、クライアントがさらに多くのデータを送信している間、常に最大 1024 サイズになります!! そのため、データをシリアル化しようとすると、次の例外が発生します: "Unterminated string. Expected delimiter: ". パス「データ」、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);
    }
}

クライアント側でバッファ サイズを定義または変更できる場所がわかりません。

何か案が?!

4

1 に答える 1

5

基本的な問題は、十分に読んでいないことです。が false の場合は読み取り操作を繰り返す必要があり、PipeStream.IsMessageCompletetrue が返されるまでそれを続ける必要があります。これは、メッセージ全体が読み取られたことを示します。デシリアライザーによっては、独自のバッファーにデータを格納するか、これを処理するためのラッパー ストリームを作成する必要がある場合があります。

これが単純な文字列の逆シリアル化でどのように機能するかの簡単な例:

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生の TCP ストリームを使用する場合でも、 /を使用StreamReaderすることは、ネットワーク シナリオではお勧めできません。それは設計されたものではありません。

于 2015-08-11T08:22:24.383 に答える