内存流复制到网络流问题
我这里的代码有问题。
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms,SerializableClassOfDoom);
ms.Position = 0;
byte[] messsize = BitConverter.GetBytes(ms.Length);
ms.Write(messsize, 0, messsize.Length);
NetworkStream ns = Sock.GetStream();
ms.CopyTo(ns);
//ms.Close();
}
我不明白这里发生了什么,或者为什么它不起作用。看起来它不复制,或者它关闭网络流,或者其他什么。
抱歉,我已经尝试调试它,但如果有人能在这里看到任何明显的问题,我将不胜感激。
顺便说一句,该类序列化得很好,并且 MemoryStream 包含数据,但由于某种原因,执行 ms.CopyTo(ns) 似乎不起作用?
本质上,我想要做的是将类序列化到网络流,并在其前面添加序列化数据的大小。如果有人有更好的方法来做到这一点,请告诉我!
I'm having a problem with this code here.
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms,SerializableClassOfDoom);
ms.Position = 0;
byte[] messsize = BitConverter.GetBytes(ms.Length);
ms.Write(messsize, 0, messsize.Length);
NetworkStream ns = Sock.GetStream();
ms.CopyTo(ns);
//ms.Close();
}
I can't figure out what's happening here, or why it's not working. It seems like eather it doesn't copy, or it closes the network stream, or something.
I'm sorry, I've tried debugging it, but if anyone can see any obvious problem here, I would appreciate it.
By the way, the class serializes fine, and the MemoryStream contains the data, but for some reason doing a ms.CopyTo(ns) just doesn't seem to work?
Essentially what I want to do is serialize the class to the network stream, with the size of the serialized data preceding it. If someone has a better way to do this let me know!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您在错误的时间重置了流位置。
在您的情况下,您将“长度”写入流的开头。
以下内容应该有效:
更新:
要将“length”写入开头,请使用临时流/字节[]。
示例:
更新 2:
更有效的方式。
You are resetting the stream position at the wrong time.
In your case, you write the 'length' to the beginning of the stream.
The following should work:
Update:
For writing 'length' to the start, use a temporary stream/byte[].
Example:
Update 2:
More efficient way.
也许您需要在调用 CopyTo 之前将内存流倒回到开头(使用 ms.Seek(0, SeekOrigin.Start))
Maybe you need to rewind the memory stream to the beginning before calling CopyTo (use ms.Seek(0, SeekOrigin.Start))
我没有看到真正的问题,但我在这里看到了一个小重构问题。
在完成任何 Stream 之前尝试使用
。
还用这样的
try-catch
语句包围它,以确保即使出现异常也会发生关闭和刷新!您的代码看起来像
这样,之后您应该能够找到您的问题。
I don't see a real problem but i see a litte refactoring issue here.
Try using
before finishing any Stream.
Also surround it with
try-catch
statements like this, to ensure closing and flushing happens even if there is an exception!Your code would look like
After this you should be able to find your problem.