C#套接字重构(数据发送)

时间:2010-12-13 11:36:28

标签: c# sockets networking refactoring

想象一下,Byte[] refArchiveData的大小约为30-100 MB。我想使用NetworkStream stream对象将其发送到服务器:

            TcpClient client = new TcpClient(server, port);

            Byte[] refLengthBytes = new Byte[4];
            Byte[] refArchiveData = null;

            refArchiveData = File.ReadAllBytes("C:/Temp/Python25.zip");

            Console.WriteLine("Archive data length is {0}", refArchiveData.Length);

            NetworkStream stream = client.GetStream();

            refLengthBytes = System.BitConverter.GetBytes(refArchiveData.Length);

            stream.Write(refLengthBytes, 0, 4);

            stream.Write(refArchiveData, 0, refArchiveData.Length);

            stream.Close();

            client.Close();

我如何修改我发送档案的代码部分?也许用256-512字节的块分割它?

感谢您的任何建议!

1 个答案:

答案 0 :(得分:7)

使用Stream.CopyTo方法。这样您就不必将整个文件加载到数组中(到内存中)。

using (var file = File.OpenRead("<path to file>"))
using (var client = new TcpClient("<server>", <port>))
using (var netStream = client.GetStream())
{
    ...
    file.CopyTo(netStream);
    ...
}