如何接收通过TCP文件,该文件是使用socket.FileSend方法发送 [英] How to receive a file over TCP which was sent using socket.FileSend Method

查看:225
本文介绍了如何接收通过TCP文件,该文件是使用socket.FileSend方法发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个客户端应用程序和服务器的。



我想从一台机器发送文件给对方,这样看来插座。<一个HREF =htt​​p://msdn.microsoft.com/en-us/library/sx0a40c2.aspx> FileSend 方法正是我要找的。

但由于没有一个FileReceive方法,我应该怎么才能接收文件在服务器端呢? (我的问题是,因为该文件将具有可变大小,将会比任何缓冲更大,我可以创造GB秩序...)


解决方案

在服务器端,您可以使用的TcpListener 并一旦客户端连接成块读取流,并将其保存到一个文件:

 类节目
{
静态无效的主要()
{
变种监听器=新的TcpListener(IPAddress.Loopback,11000);
listener.Start();而(真)
{
使用
(VAR的客户= listener.AcceptTcpClient()),使用(VAR流= client.GetStream())
使用
(VAR输出= File.Create(result.dat))
{
Console.WriteLine(客户端连接开始接收文件。);

//读取1KB
变种缓冲大块文件=新的字节[1024];
INT读取动作;
而((读取动作= stream.Read(缓冲液,0,buffer.Length))大于0)
{
output.Write(缓冲液,0,读取动作);
}
}
}

}
}

至于发送来讲你可能看看的的 SENDFILE 方法。



这是说,你也可以看看一个更强大的解决方案,就是使用WCF。有协议,如MTOM这是专门为通过HTTP发送的二进制数据进行了优化。它是相对于靠插座,这是非常低的水平更加强大的解决方案。你将不得不处理事情像文件名,大概是元数据,...这已经在现有的协议,考虑的事情。


I have a client application, and a server one.

I want to send a file from one machine to the other, so it seems the socket.FileSend method is exactly what I'm looking for.

But since there isn't a FileReceive method what should I do on the server side in order to receive a file? (My problem is because the file will have a variable size, and will be bigger than any buffer I can create GB order...)

解决方案

On the server side you could use a TcpListener and once a client is connected read the stream in chunks and save it to a file:

class Program
{
    static void Main()
    {
        var listener = new TcpListener(IPAddress.Loopback, 11000);
        listener.Start();
        while (true)
        {
            using (var client = listener.AcceptTcpClient())
            using (var stream = client.GetStream())
            using (var output = File.Create("result.dat"))
            {
                Console.WriteLine("Client connected. Starting to receive the file");

                // read the file in chunks of 1KB
                var buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    output.Write(buffer, 0, bytesRead);
                }
            }
        }

    }
}

As far as the sending is concerned you may take a look at the example provided in the documentation of the SendFile method.

This being said you might also take a look at a more robust solution which is to use WCF. There are protocols such as MTOM which are specifically optimized for sending binary data over HTTP. It is a much more robust solution compared to relying on sockets which are very low level. You will have to handle things like filenames, presumably metadata, ... things that are already taken into account in existing protocols.

这篇关于如何接收通过TCP文件,该文件是使用socket.FileSend方法发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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