I have this code:
public static void SerializeRO(Stream stream, ReplicableObject ro) {
MemoryStream serializedObjectStream = new MemoryStream();
Formatter.Serialize(serializedObjectStream, ro);
Memor开发者_StackOverflowyStream writeStream = new MemoryStream();
BinaryWriter bw = new BinaryWriter(writeStream);
bw.Write(serializedObjectStream.Length);
serializedObjectStream.Seek(0, SeekOrigin.Begin);
serializedObjectStream.WriteTo(writeStream);
serializedObjectStream.Close();
writeStream.WriteTo(stream);
bw.Close();
}
The line writeStream.WriteTo(stream);
never finishes. The program gets to that line and won't progress.
stream
is always a NetworkStream
. I've checked and I think it's a valid object (at least it's not null
nor disposed).
So what's going on?
I tried your code - writing to a FileStream
- and I always get zero bytes written to the stream. I don't know why WriteTo
would block on a NextWorkStream
when there's nothing to write, but that could be a problem
When I extract the bytes from the MemoryStream
and write them directly to stream everything works e.g. (I'm creating a binary formatter in the routine, it seems you already have a formatter).
public static void SerializeRO(Stream stream, object ro)
{
MemoryStream serializedObjectStream = new MemoryStream();
var f = new BinaryFormatter();
f.Serialize(serializedObjectStream, ro);
MemoryStream writeStream = new MemoryStream();
BinaryWriter bw = new BinaryWriter(writeStream);
var bytes = serializedObjectStream.ToArray();
bw.Write(bytes.Length);
bw.Write(bytes);
var bwBytes = writeStream.ToArray();
stream.Write(bwBytes, 0, bwBytes.Length);
bw.Close();
}
However I'd do it like this with one MemoryStream
and writing directly to stream
, unless there's something I don't know about NetworkStream
(this will of course close stream
which may not be what you want)
public static void SerializeRO(Stream stream, object ro)
{
byte[] allBytes;
using (var serializedObjectStream = new MemoryStream())
{
var f = new BinaryFormatter();
f.Serialize(serializedObjectStream, ro);
allBytes = serializedObjectStream.ToArray();
}
using (var bw = new BinaryWriter(stream))
{
bw.Write(allBytes.Length);
bw.Write(allBytes);
}
}
Version that won't close your NetworkStream (just don't put the binary writer in a using statement or Close()
it)
public static void SerializeRO(Stream stream, object ro)
{
byte[] allBytes;
using (var serializedObjectStream = new MemoryStream())
{
var f = new BinaryFormatter();
f.Serialize(serializedObjectStream, ro);
allBytes = serializedObjectStream.ToArray();
}
var bw = new BinaryWriter(stream)
bw.Write(allBytes.Length);
bw.Write(allBytes);
}
Just my thoughts: try to close your BinaryWriter
before writing stream to another. While your writer is opened stream is not finished and as the result WriteTo
newer will find the end of the stream.
精彩评论