c# - 客户端/服务器发送大文件

标签 c# .net tcp tcplistener httplistener

关闭。这个问题是opinion-based .它目前不接受答案。












想改善这个问题吗?更新问题,以便可以通过 editing this post 用事实和引文回答问题.

6年前关闭。




Improve this question




我即将编写一个服务器应用程序,它应该能够从多个来源接收大文件(像所有其他 FTP 客户端/服务器应用程序一样安静)。

但我不确定什么是最好的方法,需要一些建议。

客户端会将 XML 数据发送到服务器,它看起来像:

<Data xmlns="http://schemas.datacontract.org/2004/07/DataFiles" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <Category>General</Category>
    <Files>
        <DataFile>
            <Extension>.txt</Extension>
            <Filename>test4</Filename>
            <Bytes>"Some binary data"</Bytes>
        </DataFile>
    </Files>
</Data>

我开始创建一个 HTTPListener 作为我的服务器,但它似乎在服务器端的大文件上挣扎很多(基本上是因为上下文是作为一个未分段的数据包接收的,并且当服务器对收到的 XML 数据进行反序列化时,它会将其加载到内存中,这将对于大文件来说是不行的。

然后我转到了 TcpListener 再低一层,这似乎在大文件上工作得很好,因为它们是碎片发送的,但是让我做很多工作来在收到请求时在服务器端附加包。

我也搬过去了 WCF 作为一种可能性,但我对这项技术缺乏经验,这让我再次放弃了这种方法。

你会怎么做? 您会使用 .NET 工具箱中的哪个 .NET 工具来创建 FTP 服务器/客户端?

有很多关于 TcpListeners 等的线索,这不是我在这里寻求的。我需要关于我应该采用哪种方法和最佳实践的建议。

编辑:
忘了提到它背后的想法更像是一个FTP代理(客户端发送文件到服务器>服务器本地存储文件>服务器将其发送到第三部分位置>服务器在将文件成功发送到第三部分位置时清除本地存储的文件完毕)。

编辑 17-11-15:

这是我如何做我的 HTTP 服务器的示例代码:
public class HttpServer
{
    protected readonly HttpListener HttpListener = new HttpListener();

    protected HttpServer(IEnumerable<string> prefixes)
    {
        HttpListener.Prefixes.Add(prefix);
    }

    public void Start()
    {
        while (HttpListener.IsListening && Running)
        {
            var result = HttpListener.BeginGetContext(ContextReceived, HttpListener);
            if (WaitHandle.WaitAny(new[] {result.AsyncWaitHandle, _shutdown}) == 0)
                return;
        }
    }

    protected object ReadRequest(HttpListenerRequest request)
    {
        using (var input = request.InputStream)
        using (var reader = new StreamReader(input, request.ContentEncoding))
        {
            var data = reader.ReadToEnd();
            return data;
        }
    }

    protected void ContextReceived(IAsyncResult ar)
    {
        HttpListenerContext context = null;
        HttpListenerResponse response = null;
        try
        {
            var listener = ar.AsyncState as HttpListener;
            if (listener == null) throw new InvalidCastException("ar");
            context = listener.EndGetContext(ar);
            response = context.Response;
            switch (context.Request.HttpMethod)
            {
                case WebRequestMethods.Http.Post:
                    // Parsing XML data with file at LARGE byte[] as one of the parameter, seems to struggle here...
                    break;
                default:
                    //Send MethodNotAllowed response..
                    break;
            }
            response.Close();
        }
        catch(Exception ex)
        {
            //Do some properly exception handling!!
        }
        finally
        {
            if (context != null)
            {
                context.Response.Close();
            }
            if (response != null)
                response.Close();
        }
    }
}

客户正在使用:
using (var client = new WebClient())
{
    GetExtensionHeaders(client.Headers);
    client.Encoding = Encoding.UTF8;
    client.UploadFileAsync(host, fileDialog.FileName ?? "Test");
    client.UploadFileCompleted += ClientOnUploadFileCompleted;
    client.UploadProgressChanged += ClientOnUploadProgressChanged;
}

请注意,客户端应该将数据(作为 XML)发送到服务器,这将反序列化接收到的数据(使用文件流服务器端),如前所述。

这是我的 TcpServer 示例:
public class TcpServer
{
    protected TcpListener Listener;
    private bool _running;

    public TcpServer(int port)
    {
        Listener = new TcpListener(IPAddress.Any, port);
        Console.WriteLine("Listener started @ {0}:{1}", ((IPEndPoint)Listener.LocalEndpoint).Address, ((IPEndPoint)Listener.LocalEndpoint).Port);
        _running = true;
    }

    protected readonly ManualResetEvent TcpClientConnected = new ManualResetEvent(false);
    public void Start()
    {
        while (_running)
        {
            TcpClientConnected.Reset();
            Listener.BeginAcceptTcpClient(AcceptTcpClientCallback, Listener);
            TcpClientConnected.WaitOne(TimeSpan.FromSeconds(5));
        }
    }

    protected void AcceptTcpClientCallback(IAsyncResult ar)
    {
        try
        {
            var listener = ar.AsyncState as TcpListener;
            if (listener == null) return;

            using (var client = listener.EndAcceptTcpClient(ar))
            {
                using (var stream = client.GetStream())
                {
                    //Append or create to file stream
                }
            }

            //Parse XML data received?
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        finally
        {
            TcpClientConnected.Set();
        }
    }
}   

最佳答案

创建一个新的空 MVC 应用程序

enter image description here

接下来添加一个新的 Controller 到 Controllers文件夹,

using System.Web;
using System.Web.Mvc;

namespace UploadExample.Controllers
{
    public class UploadController : Controller
    {
        public ActionResult File(HttpPostedFileBase file)
        {
            file.SaveAs(@"c:\FilePath\" + file.FileName);
        }

    }
}

现在上传文档所需要做的就是将其作为多部分表单数据发布到您的网站...
void Main()
{   
    string fileName = @"C:\Test\image.jpg";
    string uri = @"http://localhost/Upload/File";
    string contentType = "image/jpeg";

    Http.Upload(uri, fileName, contentType);
}

public static class Http
{
    public static void Upload(string uri, string filePath, string contentType)
    {
        string boundary         = "---------------------------" + DateTime.Now.Ticks.ToString("x");
        byte[] boundaryBytes    = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

        string formdataTemplate = "Content-Disposition: form-data; name=file; filename=\"{0}\";\r\nContent-Type: {1}\r\n\r\n";
        string formitem         = string.Format(formdataTemplate, Path.GetFileName(filePath), contentType);
        byte[] formBytes        = Encoding.UTF8.GetBytes(formitem);

        HttpWebRequest request  = (HttpWebRequest) WebRequest.Create(uri);
        request.KeepAlive       = true;
        request.Method          = "POST";
        request.ContentType     = "multipart/form-data; boundary=" + boundary;
        request.SendChunked     = true;

        using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
            requestStream.Write(formBytes, 0, formBytes.Length);

            byte[] buffer = new byte[1024*4];
            int bytesLeft;

            while ((bytesLeft = fileStream.Read(buffer, 0, buffer.Length)) > 0) requestStream.Write(buffer, 0, bytesLeft);

            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
        }

        using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
        {
        }

        Console.WriteLine ("Success");    
    }
}

编辑

如果您遇到问题,请编辑您的 Web.Config 文件,您可能会遇到请求长度限制...
<system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"  maxRequestLength="1048576"/>
</system.web>

我错过的另一件事(但现在已编辑)是 webrequest 本身的发送分 block 属性。
request.SendChunked = true;

关于c# - 客户端/服务器发送大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33737790/

相关文章:

c# - 使用 StringBuilder(ASP.NET、C#)时添加新行

linux - 如何在Linux Cent OS中查找每个进程允许的TCP连接总数和TIME_WAIT值

c# - 我如何在 boo 中使用扩展方法

c# - lambda 外部子查询迭代变量评估的次数

c# - UWP - 绑定(bind)数据不起作用 - 空 ListView

.net - oData v4 简单来说什么是函数和 Action ?

.net - 查找没有任何文本节点的所有节点

.net - 函数内的 jQuery Overlay

networking - 用户模式下的 MPTCP

sql-server - ADO.NET SQLServer : How to prevent closed connection from holding S-DB lock?