WCF 用netTcpbinding,basicHttpBinding 传输大文件
问题:WCF如何传输大文件
方案:主要有几种绑定方式netTcpbinding,basicHttpBinding,wsHttpbinding,设置相关的传输max消息选项,服务端和客户端都要设置,transferMode可以buffer,stream.
实例:netTcpbinding
直接代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.IO;
using System.Runtime.Serialization; namespace FileWcfService
{
[ServiceContract(Name="KuoFileUpload",Namespace="http://www.xinvu.com/")]
public interface IFileUpload
{ [OperationContract]
void Upload(byte[] file); //[OperationContract] //此用于流模式
//void UploadStream(FileMessage fileMessage);
} //[MessageContract]
//public class FileMessage
//{
// [MessageHeader]
// public string FileName; // [MessageBodyMember]
// public Stream FileData;
//}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.IO;
using System.IO.Compression; namespace FileWcfService
{
[ServiceBehavior(Name = "MyFileUpload")]
public class FileUpload : IFileUpload
{
public void Upload(byte[] file)
{
try
{
Console.WriteLine(file.Length);
MemoryStream ms = new MemoryStream(file);
GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress);
MemoryStream msTemp = new MemoryStream();
gzip.CopyTo(msTemp);
string path= @"E:\abc"+DateTime.Now.Ticks.ToString()+".rar"; //简单重命名
Console.WriteLine(path);
File.WriteAllBytes(path, msTemp.ToArray());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
} //public void UploadStream(FileMessage fileMessage)
//{
// string path = @"e:\" + fileMessage.FileName + DateTime.Now.Ticks.ToString() + ".rar"; // //简单重命名
// try
// {
// FileStream fs = new FileStream(path, FileMode.CreateNew);
// fileMessage.FileData.CopyTo(fs);
// fs.Flush();
// fs.Close();
// }
// catch (Exception ex)
// {
// Console.WriteLine(ex.Message);
// }
//}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel; namespace FileWcfService
{
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(FileUpload)))
{
if (host.State != CommunicationState.Opened)
host.Open();
Console.WriteLine("服务已启动……");
Console.WriteLine();
Console.Read();
} }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.IO.Compression; namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ } protected void Button1_Click(object sender, EventArgs e)
{
DateTime date = DateTime.Now;
FileUpload.KuoFileUploadClient file = new FileUpload.KuoFileUploadClient();
byte[] buffer = this.FileUpload1.FileBytes;
MemoryStream ms = new MemoryStream();
GZipStream zip = new GZipStream(ms, CompressionMode.Compress);
zip.Write(buffer, , buffer.Length);
byte[] buffer_zip = ms.ToArray();
zip.Close();
ms.Close();
//If the file bigger than 100MB, usually, there will be fault:
//Failed to allocate a managed memory buffer of 208073270 bytes. The amount of available memory may be low.
//I don't know how to salve this solution.So, please use stream mode.
file.Upload(buffer_zip);
zip.Close();
Response.Write(date.ToString() + "---" + DateTime.Now.ToString() + "<br/> Before:" + buffer.Length + ":After" + buffer_zip.ToString() + "<br/>");
Response.Write(FileUpload1.FileName); } protected void Button2_Click(object sender, EventArgs e)
{
//DateTime date = DateTime.Now;
//FileUpload.KuoFileUploadClient file = new FileUpload.KuoFileUploadClient(); //FileUpload.FileMessage filedata = new FileUpload.FileMessage(); //using (MemoryStream ms = new MemoryStream())
//{
// filedata.FileName = this.FileUpload1.FileName;
// filedata.FileData = this.FileUpload1.PostedFile.InputStream;
// file.UploadStream(filedata);
// Response.Write(date.ToString() + "---" + DateTime.Now.ToString() + "<br/>");
// Response.Write(FileUpload1.FileName); //}
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<!--
流模式启用netTcpBindConfig,buffer启用netTcpBindingBuffer,人懒
--> <!--<netTcpBinding>
<binding name="netTcpBindConfig"
closeTimeout="00:10:00"
openTimeout="00:10:00"
receiveTimeout="00:10:00"
sendTimeout="00:10:00"
transactionFlow="false"
transferMode="Streamed"
transactionProtocol="OleTransactions"
hostNameComparisonMode="StrongWildcard"
listenBacklog="10"
maxBufferPoolSize="2147483647 "
maxBufferSize="2147483647 "
maxConnections="10"
maxReceivedMessageSize="2147483647 "
>
<readerQuotas maxDepth="32" maxArrayLength="2147483647" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="Transport">
<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
</security>
</binding> </netTcpBinding>--> <netTcpBinding>
<binding name="netTcpBindingBuffer"
closeTimeout="00:10:00"
openTimeout="00:10:00"
receiveTimeout="00:10:00"
sendTimeout="00:10:00"
transactionFlow="false"
transferMode="Buffered"
transactionProtocol="OleTransactions"
hostNameComparisonMode="StrongWildcard"
listenBacklog="10"
maxBufferPoolSize="2147483647 "
maxBufferSize="2147483647 "
maxConnections="10"
maxReceivedMessageSize="2147483647 "
>
<readerQuotas maxDepth="32" maxArrayLength="2147483647" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="Transport">
<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
</security>
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="MyFileUpload">
<serviceMetadata />
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="FileWcfService.FileUpload" behaviorConfiguration="MyFileUpload">
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:8089/FileService"/>
</baseAddresses>
</host>
<!--<endpoint address="" binding="netTcpBinding"
contract="FileWcfService.IFileUpload" bindingConfiguration="netTcpBindConfig" ></endpoint>-->
<endpoint address=""
binding="netTcpBinding"
contract="FileWcfService.IFileUpload"
bindingConfiguration="netTcpBindingBuffer" ></endpoint>
<endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" ></endpoint>
</service>
</services>
</system.serviceModel>
</configuration>
实例二:basicHttpBinding ,实验上传1.5G没问题,局域网
新建一个web站点,加入一个wcf data service.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.IO; namespace WcfService1
{
// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IService1”。
[ServiceContract]
public interface IGetDataService
{
[OperationContract]
void UploadFile(FileData file);
}
[MessageContract]
public class FileData
{
[MessageHeader]
public string filename;
[MessageBodyMember]
public Stream data;
} }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.IO; namespace WcfService1
{
public class GetDataService : IGetDataService
{
public void UploadFile(FileData file)
{ FileStream fs = new FileStream("D:\\" + file.filename, FileMode.OpenOrCreate); try
{ BinaryReader reader = new BinaryReader(file.data); byte[] buffer; BinaryWriter writer = new BinaryWriter(fs);
long offset = fs.Length;
writer.Seek((int)offset, SeekOrigin.Begin); do
{ buffer = reader.ReadBytes(); writer.Write(buffer); } while (buffer.Length > ); fs.Close();
file.data.Close(); }
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{ fs.Close();
file.data.Close(); } }
}
}
protected void Button1_Click(object sender, EventArgs e)
{
FileData file = new FileData();
file.filename = FileUpload1.FileName;
file.data = FileUpload1.PostedFile.InputStream;
GetDataService c = new GetDataService();
c.UploadFile(file);
Response.Write("文件传输成功!");
}
<?xml version="1.0" encoding="utf-8"?>
<configuration> <system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime maxRequestLength="2147483647" />
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IGetDataService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="01:10:00" sendTimeout="01:10:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" transferMode="Streamed" useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None" realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:52884/mex" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IGetDataService" contract="IGetDataService" name="BasicHttpBinding_IGetDataService" />
</client>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" /></system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer> </configuration>
WCF 用netTcpbinding,basicHttpBinding 传输大文件的更多相关文章
- WCF利用Stream上传大文件
WCF利用Stream上传大文件 转自别人的文章,学习这个例子,基本上wcf也算入门了,接口用法.系统配置都有了 本文展示了在asp.net中利用wcf的stream方式传输大文件,解决了大文件上传问 ...
- C# 的 WCF文章 消息契约(Message Contract)在流(Stream )传输大文件中的应用
我也遇到同样问题,所以抄下做MARK http://www.cnblogs.com/lmjq/archive/2011/07/19/2110319.html 刚做完一个binding为netTcpBi ...
- 基于RMI服务传输大文件的完整解决方案
基于RMI服务传输大文件,分为上传和下载两种操作,需要注意的技术点主要有三方面,第一,RMI服务中传输的数据必须是可序列化的.第二,在传输大文件的过程中应该有进度提醒机制,对于大文件传输来说,这点很重 ...
- linux传输大文件
http://dreamway.blog.51cto.com/1281816/1151886 linux传输大文件
- 使用QQ传输大文件
现在在公网上能传输大文件并且稳定支持断点续传的软件非常少了,可以使用qq来做这件事. qq传输单个文件有时候提示不能超过4g有时候提示不能超过60g,没搞明白具体怎么样. 可以使用qq的传输文件夹功能 ...
- TCP协议传输大文件读取时候的问题
TCP协议传输大文件读取时候的问题 大文件传不完的bug 我们在定义的时候定义服务端每次文件读取大小为10240, 客户端每次接受大小为10240 我们想当然的认为客户端每次读取大小就是10240而把 ...
- wcf综合运用之:大文件异步断点续传
在WCF下作大文件的上传,首先想到使用的就是Stream,这也是微软推荐的使用方式.处理流程是:首先把文件加载到内存中,加载完毕后传递数据.这种处理方式对小文件,值得推荐,比如几K,几十k的图片文件, ...
- rsync增量传输大文件优化技巧
问题 rsync用来同步数据非常的好用,特别是增量同步.但是有一种情况如果不增加特定的参数就不是很好用了.比如你要同步多个几十个G的文件,然后网络突然断开了一下,这时候你重新启动增量同步.但是发现等了 ...
- Samba共享传输大文件(ex:1G)失败的问题
1:问题描述 1.1 基本信息 遇见这样一个bug,路由器有USB share的功能,可将U盘内的文件通过samba和LAN端PC机中文件进行共享,测试发现小文件可正常共享,一旦文件大了(比如1G左右 ...
随机推荐
- 用了OneAPM CT,宕机早知道!
Twitter 的公司网站和移动应用在 1 月 19 日早上出现宕机,导致全球部分地区用户无法正常访问.这次宕机影响了很多用户,英国和印度用户已经无法访问 Twitter .第三方监测机构 DownD ...
- iOS-NSString-Base64String-Base64原理
之前看到好多人找Str2Base64Str,还有好多自己写了方法的,仔细研究了下base64的编码原理(这个我写在下面),发现官方的API已经可以完成这项功能,这里贴出来供大家参考. 一言不合就上代码 ...
- 事务Isolation Level 例子详解
举例分析: 我们有A表, 包含两条数据. Read uncommitted: 假设我们有两个事务 Trans1, Trans2. 它们的操作如下: Trans 1: 更新A1 -> A11, 然 ...
- bzoj1212
trie树最基本的应用了不难得到f[i]=f[j] if (s[j+1~i]∈dictionary);可以用trie树匹配 ..] of boolean; son:..,..] of longint; ...
- Azure SQL 数据库的灵活缩放预览版简介
Eron Kelly SQL Server 产品管理部门产品市场营销总经理 几天前,我们宣布了发布 Azure SQL 数据库的灵活缩放公共预览版.新增的灵活缩放功能通过简化开发和管理,简化了扩展和缩 ...
- java基础(十三)常用类总结(三)
这里有我之前上课总结的一些知识点以及代码大部分是老师讲的笔记 个人认为是非常好的,,也是比较经典的内容,真诚的希望这些对于那些想学习的人有所帮助! 由于代码是分模块的上传非常的不便.也比较多,讲的也是 ...
- How to disable Eclipse splash
Run eclipse with the -nosplash option.
- poj 3259 Wormholes【spfa判断负环】
Wormholes Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 36729 Accepted: 13444 Descr ...
- win7限制登录时间的设置方法
win7使用Net User命令行语句限制登录时间的方法: 1.单击“开始”,然后单击“运行”. 2.在“打开”框中,键入cmd,然后单击“确定”. 3..键入 net user username / ...
- java传递json数据到前台jsp
在数据传输流程中,json是以文本,即字符串的形式传递的,而JS操作的是JSON对象,所以,JSON对象和JSON字符串之间的相互转换是关键.例如: JSON字符串: var str1 = '{ &q ...