【发布时间】: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,这将产生单独的消息。