using System;
using System.IO;
using System.Runtime.Serialization;
using System.ServiceModel; namespace WcfServer
{
internal class Program
{
private static void Main()
{
using (var host = new ServiceHost(typeof (StreamServices)))
{
host.Opened += (a, b) => Console.WriteLine("...");
host.Open(); Console.ReadKey();
}
}
} [ServiceContract(Name = "IStreamServices",
SessionMode = SessionMode.Required,
Namespace = "http://www.msdn.com/IStreamServices/14/04/11")]
public interface IStreamServices
{
[OperationContract(Name = "Upload")]
FileInformation Upload(FileInformation fileInfo); [OperationContract(Name = "Download")]
FileInformation Download(FileInformation fileInfo);
} [ServiceBehavior(Name = "StreamServices",
Namespace = "http://www.msdn.com/StreamServices/14/04/11"
, InstanceContextMode = InstanceContextMode.PerCall,
ConcurrencyMode = ConcurrencyMode.Multiple)]
public class StreamServices : IStreamServices
{
private static readonly string AttachmentPath = AppDomain.CurrentDomain.BaseDirectory + "Attachments//"; #region IServices 成员 public FileInformation Upload(FileInformation fileInfo)
{
try
{
if (fileInfo == null)
return new FileInformation {Error = "FileInformation对象不能为空"};
if (string.IsNullOrEmpty(fileInfo.FileNameNew))
fileInfo.FileNameNew = Guid.NewGuid() + fileInfo.FileSuffix;
var savePath = AttachmentPath + fileInfo.FileNameNew;
using (var fs = new FileStream(savePath, FileMode.OpenOrCreate))
{
long offset = fileInfo.Offset;
using (var write = new BinaryWriter(fs))
{
write.Seek((int) offset, SeekOrigin.Begin);
write.Write(fileInfo.Data);
fileInfo.Offset = fs.Length;
}
}
return fileInfo;
}
catch (IOException ex)
{
return new FileInformation {Error = ex.Message};
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
return new FileInformation {Error = "wcf内部错误"};
}
} public FileInformation Download(FileInformation fileInfo)
{
try
{
if (fileInfo == null)
return new FileInformation {Error = "FileInformation对象不能为空"};
var readFileName = AttachmentPath + fileInfo.FileName;
if (!File.Exists(readFileName))
return new FileInformation {Error = "DirectoryNotFoundException"};
var stream = File.OpenRead(readFileName);
fileInfo.Length = stream.Length;
if (fileInfo.Offset.Equals(fileInfo.Length))
return new FileInformation {Offset = fileInfo.Offset, Length = stream.Length};
var maxSize = fileInfo.MaxSize > * ? * : fileInfo.MaxSize;
fileInfo.Data =
new byte[fileInfo.Length - fileInfo.Offset <= maxSize ? fileInfo.Length - fileInfo.Offset : maxSize];
stream.Position = fileInfo.Offset;
stream.Read(fileInfo.Data, , fileInfo.Data.Length);
return fileInfo;
}
catch (IOException ex)
{
return new FileInformation {Error = ex.Message};
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
return new FileInformation {Error = "wcf内部错误"};
}
} #endregion
} [DataContract(Name = "MyStreamInfo")]
public class FileInformation
{
[DataMember(Name = "Length", IsRequired = true)]
public long Length { get; set; } [DataMember(Name = "FileName", IsRequired = true)]
public string FileName { get; set; } [DataMember(Name = "Data")]
public byte[] Data { get; set; } [DataMember(Name = "FileSuffix")]
public string FileSuffix { get; set; } [DataMember(Name = "Offset", IsRequired = true)]
public long Offset { get; set; } [DataMember(Name = "Error")]
public string Error { get; set; } private int maxSize = *; //200k [DataMember(Name = "MaxSize")]
public int MaxSize
{
get { return maxSize; }
set { maxSize = value; }
} [DataMember(Name = "KeyToken")]
public string KeyToken { get; set; } [DataMember(Name = "FileNameNew")]
public string FileNameNew { get; set; }
}
}
 using System;
using System.IO;
using WcfClientApp.ServiceReference1; namespace WcfClientApp
{
internal class Program
{
private static void Main()
{
Upload();
Download();
Console.ReadKey();
} /// <summary>
/// 上传
/// </summary>
private static void Upload()
{
try
{
var filePath = AppDomain.CurrentDomain.BaseDirectory + "UploadFiles//张国荣 - 共同度过.mp3";
const string fileName = "张国荣 - 共同度过.mp3";
const int maxSize = *;
if (!File.Exists(filePath))
{
Console.WriteLine("DirectoryNotFoundException");
return;
}
FileStream stream = File.OpenRead(filePath);
var fileInfo = new MyStreamInfo {Length = stream.Length, FileName = fileName,FileSuffix=".mp3"};
using (var client = new StreamServicesClient())
{
while (fileInfo.Length != fileInfo.Offset)
{
fileInfo.Data =
new byte[
fileInfo.Length - fileInfo.Offset <= maxSize
? fileInfo.Length - fileInfo.Offset
: maxSize];
stream.Position = fileInfo.Offset;
stream.Read(fileInfo.Data, , fileInfo.Data.Length);
fileInfo = client.Upload(fileInfo);
if (!string.IsNullOrEmpty(fileInfo.Error))
{
Console.WriteLine(fileInfo.Error);
break;
}
}
if (fileInfo.Length.Equals(fileInfo.Offset))
Console.WriteLine("Upload successful!");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// 下载
/// </summary>
private static void Download()
{
try
{
var filePath = AppDomain.CurrentDomain.BaseDirectory +
"DownloadFiles//c228d4df-8bdc-468b-96ec-46860c2f026a.mp3";
const string fileName = "c228d4df-8bdc-468b-96ec-46860c2f026a.mp3";
var fileInfo = new MyStreamInfo {FileName = fileName, Length = , MaxSize = *};
using (var client = new StreamServicesClient())
{
while (fileInfo.Length != fileInfo.Offset)
{
fileInfo = client.Download(fileInfo);
if (!string.IsNullOrEmpty(fileInfo.Error))
{
Console.WriteLine(fileInfo.Error);
break;
}
using (var fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
long offset = fileInfo.Offset;
using (var write = new BinaryWriter(fs))
{
write.Seek((int) offset, SeekOrigin.Begin);
write.Write(fileInfo.Data);
fileInfo.Offset = fs.Length;
}
}
}
if (fileInfo.Length.Equals(fileInfo.Offset))
Console.WriteLine("download successful!");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}

使用MaxSize控制下载、上传大小(k)

一开始设计的时候,我考虑使用双工模式,但是觉得有不太好,使用双工模式反而增加了代码开发量。

不知道各位有没有什么更好的解决办法?是否愿意分享一下,谢谢各位的指点。

WCF传输大数据 --断点续传(upload、download)的更多相关文章

  1. WCF传输大数据的设置

    在从客户端向WCF服务端传送较大数据(>65535B)的时候,发现程序直接从Reference的BeginInvoke跳到EndInvoke,没有进入服务端的Service实际逻辑中,怀疑是由于 ...

  2. 【转】WCF传输大数据的设置

    在从客户端向WCF服务端传送较大数据(>65535B)的时候,发现程序直接从Reference的BeginInvoke跳到EndInvoke,没有进入服务端的Service实际逻辑中,怀疑是由于 ...

  3. WCF传输大数据的设置2

    本节主要内容:1.如何读取Binding中的binding元素.2.CustomBinding元素的基本配置.3.代码示例 一.Bingding是由binding元素构成的,可以根据实际需要,进行适当 ...

  4. 快速传输大数据(tar+lz4+pv)

    快速传输大数据(tar+lz4+pv)   如果用传统SCP远程拷贝,速度是比较慢的.现在采用lz4压缩传输.LZ4是一个非常快的无损压缩算法,压缩速度在单核300MB/S,可扩展支持多核CPU.它还 ...

  5. 解决WCF传输的数据量过大问题

    今天写了个WCF接口,然后自测通过,和别人联调时报 远程服务器返回错误: (413) Request Entity Too Large        错误!记得以前写的时候也出现过这个错误,大致解决办 ...

  6. WCF传送大数据时的错误“ 超出最大字符串内容长度配额”

    格式化程序尝试对消息反序列化时引发异常: 尝试对参数 http://tempuri.org/ 进行反序列化时出错: GetLzdtArticleResult.InnerException 消息是“反序 ...

  7. php传输大数据大文件时候php.ini相关设置

    post_max_size which is directly related to the POST size---针对采用post上传的,大文件,此项为关键 upload_max_filesize ...

  8. 【转载】大数据量传输时配置WCF的注意事项

    WCF传输数据量的能力受到许多因素的制约,如果程序中出现因需要传输的数据量较大而导致调用WCF服务失败的问题,应注意以下配置: 1.MaxReceivedMessageSize:获取或设置配置了此绑定 ...

  9. WCF 传输和接受大数据

    向wcf传入大数据暂时还没找到什么好方案,大概测了一下传输2M还是可以的,有待以后解决. 接受wcf传回的大数据,要进行web.config的配置,刚开是从网上搜自己写进行配置,折磨了好长时间. 用以 ...

随机推荐

  1. python 获取5天前的日期

    from datetime import date, timedelta dt = date.today() - timedelta() print('Current Date :',date.tod ...

  2. python 字典添加元素

    d = {:, :} print(d) d.update({:}) print(d)

  3. [java]String和Date、Timestamp之间的转换

    一.String与Date(java.util.Date)互转  1.1 String -> Date Date date = DateFormat.parse(String  str); St ...

  4. 递推-练习2--noi3525:上台阶

    递推-练习2--noi3525:上台阶 一.心得 二.题目 3525:上台阶 总时间限制:  1000ms 内存限制:  65536kB 描述 楼梯有n(100 > n > 0)阶台阶,上 ...

  5. myeclipse出现src作为报名一部分src.com.*

    打开历史悠久的项目,所有类报错,发现src变成了报名的一部分. 右击src->Build Path->Use as Source Folder即可. WebRoot中同理.

  6. Java中字符串比较的注意点

    Java中必须使用string1.equals(string2)来进行判断 补充如果: string s1=new String("Hello"); string s2=new S ...

  7. POSIX线程接口编程学习心得

    由于实验需要,需要了解下C语言多线程编程的知识,于是学习了下POSIX线程编程的知识,有点心得,记录并分享一下. POSIX(可移植操作系统接口)线程是提高代码响应和性能的有力手段.与标准 fork( ...

  8. Mysql04

    mysql: dbs 数据库系统 bdms 数据库管理系统 bda 数据库管理员 db 数据库 dba通过dbms来操作db! 关系型数据库和非关系型数据库 登录mysql mysql -h主机地址 ...

  9. 安装win7和ubuntu双系统

    最近买了新的笔记本电脑,发现新买的电脑上面安装的是win7用户版,在网上查了一下这个版本的win7是功能最少的...另外又发现偌大的500G硬盘居然只给分成2个区,每个250...各种不爽,于是决定格 ...

  10. zTree简单使用

    zTree使用 zTree github地址 zTree API文档 zTree插件依赖JQ所以使用zTree首先引入JQ,另外zTree的点击功能,编辑功能都是单独的文件,如需使用也要引入(也可以引 ...