WCF开启流模式,主要是设置一个叫TransferMode的属性,所以,你看看哪些Binding的派生类有这个属性就可以了。
TransferMode其实是一个举枚,看看它的几个有效值:
上传文件的例子:
服务器端:
[MessageContract] public class TransferFileMessage { [MessageHeader] public string FileName; //文件名 [MessageBodyMember] public Stream FileStream; //文件流 } [MessageContract] public class ResultMessage { [MessageHeader] public string ErrorMessage; [MessageBodyMember] public bool IsSuccessed; } [ServiceContract] public interface IService { //消息契约作为传入参数,则只能有一个参数,返回值为void //如果需要返回值,则必须返回一个消息契约 [OperationContract] ResultMessage UploadFile(TransferFileMessage fileMessage); } public class Service : IService { public ResultMessage UploadFile(TransferFileMessage fileMessage) { ResultMessage msg = new ResultMessage(); try { using (FileStream outputStream = new FileStream(fileMessage.FileName,FileMode.OpenOrCreate)) { fileMessage.FileStream.CopyTo(outputStream); outputStream.Flush(); msg.IsSuccessed = true; Console.WriteLine("在{0}接收到客户端发送的流,已保存到{1}。", DateTime.Now.ToLongTimeString(), fileMessage.FileName); } } catch (Exception ex) { msg.ErrorMessage = ex.Message; msg.IsSuccessed = false; } return msg; } } class Program { static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(Service))) { BasicHttpBinding bingding = new BasicHttpBinding(); // 启用流模式 bingding.TransferMode = TransferMode.StreamedRequest; //缓存区的最大值 bingding.MaxBufferSize = 1024; // 接收消息的最大范围为500M bingding.MaxReceivedMessageSize = 500*1024*1024; host.AddServiceEndpoint(typeof(IService), bingding, "http://127.0.0.1:8888/service1"); ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); behavior.HttpGetEnabled = true; behavior.HttpGetUrl = new Uri("http://127.0.0.1:8888/service"); //httpGetUrl客户端引用的地址 host.Description.Behaviors.Add(behavior); host.Opened += delegate { Console.WriteLine("服务已启动"); Console.ReadKey(); }; host.Open(); } } }
客户端调用:
private void button1_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { label1.Text = ofd.FileName; } } private async void button2_Click(object sender, EventArgs e) { if (!File.Exists(label1.Text)) { return; } using (FileStream fs = new FileStream(label1.Text, FileMode.Open, FileAccess.Read)) { using (ServiceClient client = new ServiceClient()) { var result = await client.UploadFileAsync(Path.GetFileName(this.label1.Text),fs); if (result.IsSuccessed) { MessageBox.Show("上传完成"); } } } }
重温WCF之流与文件传输(七),布布扣,bubuko.com
原文:http://www.cnblogs.com/yxlblogs/p/3779474.html