内存流复制到网络流问题 [英] memorystream copyto network stream issues

查看:159
本文介绍了内存流复制到网络流问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里的这段代码有问题.

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();
}

我不知道这里发生了什么,或者为什么它不起作用.似乎eather无法复制,或者关闭了网络流,或者什么了.

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.

顺便说一句,该类可以很好地进行序列化,并且MemoryStream包含数据,但是出于某种原因执行ms.CopyTo(ns)似乎不起作用?

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!

推荐答案

您正在错误的时间重置流的位置.

You are resetting the stream position at the wrong time.

在您的情况下,您将长度"写入流的开头.

In your case, you write the 'length' to the beginning of the stream.

以下应能工作:

using (MemoryStream ms = new MemoryStream())
{
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(ms,SerializableClassOfDoom);
    byte[] messsize = BitConverter.GetBytes(ms.Length);
    ms.Write(messsize, 0, messsize.Length);
    ms.Position = 0;
    NetworkStream ns = Sock.GetStream();
    ms.CopyTo(ns);
}

更新:

要在开始处写入长度",请使用临时流/字节[].

For writing 'length' to the start, use a temporary stream/byte[].

示例:

using (MemoryStream ms = new MemoryStream())
{
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(ms,SerializableClassOfDoom);
    byte[] data = ms.ToArray();
    byte[] messsize = BitConverter.GetBytes(ms.Length);
    ms.Position = 0;
    ms.Write(messsize, 0, messsize.Length);
    ms.Write(data, 0, data.Length);
    ms.Position = 0; // again!
    NetworkStream ns = Sock.GetStream();
    ms.CopyTo(ns);
}

更新2:

更有效的方法.

using (MemoryStream ms = new MemoryStream())
{
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(ms,SerializableClassOfDoom);
    byte[] messsize = BitConverter.GetBytes(ms.Length);
    NetworkStream ns = Sock.GetStream();
    ns.Write(messsize, 0, messsize.Length);
    ms.Position = 0; // not sure if needed, doc for CopyTo unclear
    ms.CopyTo(ns); 
}

这篇关于内存流复制到网络流问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆