如何在c#中通过TCP / IP发送大文件(500MB - 1GB)?

时间:2015-10-21 05:48:36

标签: c# sockets tcpclient

我正在使用下面的代码将样本数据发送到字节流中,并且工作正常。

使用的代码

客户

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        TcpClient tcpClient = new TcpClient("localHost", 5200);

        NetworkStream networkStream = tcpClient.GetStream();
        BufferedStream bs = new BufferedStream(networkStream);


        //Send data to listener
        byte[] dataToSend = new byte[100];
        new Random().NextBytes(dataToSend);
        for (int i = 0; i < 100; i++)
            networkStream.Write(dataToSend, 0, dataToSend.Length);

        //when the network stream is closed, it also shuts down the connection
        networkStream.Close();

        Console.WriteLine("Done");
        Console.ReadLine();
    }

}

服务器

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        IPAddress ip = IPAddress.Parse("127.0.0.1");
        TcpListener tcpListener = new TcpListener(ip, 5200);
        tcpListener.Start();

        Console.WriteLine("Waiting for a client to connect...");

        //blocks until a client connects
        Socket socketForClient = tcpListener.AcceptSocket();

        Console.WriteLine("Client connected");

        //Read data sent from client
        NetworkStream networkStream = new NetworkStream(socketForClient);
        int bytesReceived, totalReceived = 0;
        byte[] receivedData = new byte[1000];
        do
        {
            bytesReceived = networkStream.Read
                (receivedData, 0, receivedData.Length);
            totalReceived += bytesReceived;
        }
        while (bytesReceived != 0);
        Console.WriteLine("Total bytes read: " + totalReceived.ToString());

        socketForClient.Close();
        Console.WriteLine("Client disconnected...");

        Console.ReadLine();
    }
}

我不知道如何从文件中以相同的方式发送大小非常大的数据。

我尝试了以下代码,但如果文件大小为30MB或更多,则无效。

public void SendTCP(string filePath, string IPA, Int32 PortN)
    {
        byte[] SendingBuffer = null;
        TcpClient client = null;
        lblStatus.Text = "";
        NetworkStream netstream = null;
        try
        {
            client = new TcpClient(IPA, PortN);
            lblStatus.Text = "Connected to the Server...\n";
            netstream = client.GetStream();
            FileStream Fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            int NoOfPackets = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(Fs.Length) / Convert.ToDouble(BufferSize)));
            progressBar1.Maximum = NoOfPackets;
            int TotalLength = (int)Fs.Length, CurrentPacketLength, counter = 0;
            for (int i = 0; i < NoOfPackets; i++)
            {
                if (TotalLength > BufferSize)
                {
                    CurrentPacketLength = BufferSize;
                    TotalLength = TotalLength - CurrentPacketLength;
                }
                else
                    CurrentPacketLength = TotalLength;
                SendingBuffer = new byte[CurrentPacketLength];
                Fs.Read(SendingBuffer, 0, CurrentPacketLength);
                netstream.Write(SendingBuffer, 0, (int)SendingBuffer.Length);
                if (progressBar1.Value >= progressBar1.Maximum)
                    progressBar1.Value = progressBar1.Minimum;
                progressBar1.PerformStep();
            }

            lblStatus.Text = lblStatus.Text + "Sent " + Fs.Length.ToString() + " bytes to the server";
            Fs.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            netstream.Close();
            client.Close();

        }
    }

1 个答案:

答案 0 :(得分:1)

应该这么简单:

// Pass a file and send it through a socket.
static async Task SendFile(FileInfo file, Socket socket)
{
    using (var networkStream = new BufferedStream(new NetworkStream(socket, false)))
    using (var fileStream = file.OpenRead())
    {
        await fileStream.CopyToAsync(networkStream);
        await networkStream.FlushAsync();
    }
}

// Pass a socket and read the content to copy it to a file.
static async Task ReceiveFile(Socket socket, FileInfo file)
{
    using (var fileStream = file.OpenWrite())
    using (var networkStream = new NetworkStream(socket, false))
    {
        await networkStream.CopyToAsync(fileStream);
    }
}

如果需要报告进度,可以使用缓冲区并报告复制的字节数:

static async Task SendFile(FileInfo file, Socket socket)
{
    var readed = -1;
    var buffer = new Byte[4096];
    using (var networkStream = new BufferedStream(new NetworkStream(socket, false)))
    using (var fileStream = file.OpenRead())
    {
        while(readed != 0)
        {
            readed = fileStream.Read(buffer, 0, buffer.Length);
            networkStream.Write(buffer, 0, readed);
            Console.WriteLine("Copied " + readed);
        }
        await networkStream.FlushAsync();
    }
}

static async Task ReceiveFile(Socket socket, FileInfo file)
{
    var readed = -1;
    var buffer = new Byte[4096];
    using (var fileStream = file.OpenWrite())
    using (var networkStream = new NetworkStream(socket, false))
    {
        while (readed != 0)
        {
            readed = networkStream.Read(buffer, 0, buffer.Length);
            fileStream.Write(buffer, 0, readed);
            Console.WriteLine("Copied " + readed);
        }
    }
}