重温WCF之流与文件传输(七)

时间:2022-10-21 07:05:49

WCF开启流模式,主要是设置一个叫TransferMode的属性,所以,你看看哪些Binding的派生类有这个属性就可以了。

TransferMode其实是一个举枚,看看它的几个有效值:

  • Buffered:缓冲模式,说白了就是在内存中缓冲,一次调用就把整个消息读/写完,也就是我们最常用的方式,就是普通的操作协定的调用方式;
  • StreamedRequest:只是在请求的时候使用流,说简单一点就是在传入方法的参数使用流,如 int MyMethod(System.IO.Stream stream);
  • StreamedResponse:就是操作协定方法返回一个流,如 Stream MyMethod(string file_name);

上传文件的例子:

服务器端:

 [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 = ;
// 接收消息的最大范围为500M
bingding.MaxReceivedMessageSize = **;
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("上传完成");
}
}
} }