如何写流内存流? [英] how to write the stream to memory stream?

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

问题描述

public void doprocess(TcpClient client)
{    
    MemoryStream ms = new MemoryStream();

    Stream clStream = client.GetStream();

    byte[] buffer_1 = new byte[8192];

    int count = clStream.Read(buffer_1, 0, buffer_1.Length);

    while (count > 0)
    {
        ms.Write(buffer_1, 0, count);

        //the below line doesn't gives response and code hangs here 
        count = clStream.Read(buffer_1, 0, buffer_1.Length);         
    }
}

有没有写一个流到另一个任何其他方式?我想用这个两次,这就是为什么我需要把它写在的MemoryStream

Is there any other way to write one stream to another? I want to use this Stream twice, which is why I need to write it to the MemoryStream.

推荐答案

在.NET 4中复制的部分是很容易的:

In .NET 4 the copying part is really easy:

MemoryStream ms = new MemoryStream();
client.GetStream().CopyTo(ms);

如果你不使用.NET 4,然后code相似,你已经得到基本相同的事情。

If you're not using .NET 4, then code similar to what you've already got is basically the same thing.

然而,请注意,如果网络流已关闭这(以及任何其他的尝试)将只工作 - 否则通话将阻止等待更多的数据。我怀疑那是什么地方出了错你 - 这是一个根本性的问题

However, note that this (and any other attempt) will only work if the network stream has been closed - otherwise the Read call will block waiting for more data. I suspect that's what's going wrong for you - and it's a fundamental problem.

如果您的网络数据流不会结束,那么它目前还不清楚你真的想表现 - 应该的分裂流基本的两个读卡器读取任何缓冲的数据,但随后被阻塞,直到有新的数据,否则?当它被从两个流读当然,缓冲的数据可以被删除。如果这就是你追求的是什么,我不觉得有什么在.NET来帮助你特别 - 它可能是pretty的棘手

If your network stream isn't closed, then it's unclear how you'd really want it to behave - should the two readers of the "split" stream basically read any buffered data, but then block until there's new data otherwise? The buffered data could be removed when it's been read from both streams, of course. If that is what you're after, I don't think there's anything in .NET to help you particularly - and it's probably pretty tricky.

如果你可以给我们你想要做什么(和TcpClient的连接是什么),这将真正帮助更多的上下文。

If you could give us more context of what you're trying to do (and what the TcpClient is connecting to) that would really help.

这篇关于如何写流内存流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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