你的位置:首页 > ASP.net教程

[ASP.net教程]WCF快速上手


    需求:在同一台机子上,有一个B/S程序,和一个C/S程序(不要问为什么,事实就是这样),B/S程序需要主动和C/S程序通信(C/S程序主动与B/S程序通信的情况这里暂不讨论)。

    下面以最快的速度写一个B/S程序和一个C/S程序实现,具体细节不解释,自己翻书看去。

    一、建了两个工程,如下图所示:

    二、先看C/S程序,跑起来就是这样的,如下图所示(简单吧):

程序结构如下图:

WCF的接口WCFServer、数据结构DataStruct、Winform程序Client

IClientServer:

using System;using System.Collections.Generic;using System.Linq;using System.ServiceModel;using System.Text;using System.Threading.Tasks;using DataStruct;namespace WCFServer{  [ServiceContract]  public interface IClientServer  {    [OperationContract]    TestData Test(string param);  }}

View Code

ClientServer:

using System;using System.Collections.Generic;using System.Linq;using System.ServiceModel;using System.Text;using System.Threading.Tasks;using DataStruct;namespace WCFServer{  [ServiceBehavior()]  public class ClientServer : IClientServer  {    /// <summary>    /// 测试    /// </summary>    public TestData Test(string param)    {      TestData data = new TestData();      data.Name = param;      data.Code = "0101";      return data;    }  }}

View Code

TestData:

using System;using System.Collections.Generic;using System.Linq;using System.Runtime.Serialization;using System.Text;using System.Threading.Tasks;namespace DataStruct{  [DataContract]  public class TestData  {    [DataMember]    public string Name { get; set; }    [DataMember]    public string Code { get; set; }  }}

View Code

Form1.cs:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.ServiceModel;using System.ServiceModel.Description;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using WCFServer;namespace CSServer{  public partial class Form1 : Form  {    public Form1()    {      InitializeComponent();    }    private void Form1_Load(object sender, EventArgs e)    {      OpenClientServer();    }    /// <summary>    /// 启动服务    /// </summary>    private void OpenClientServer()    {      WSHttpBinding wsHttp = new WSHttpBinding();      wsHttp.MaxBufferPoolSize = 524288;      wsHttp.MaxReceivedMessageSize = 2147483647;      wsHttp.ReaderQuotas.MaxArrayLength = 6553600;      wsHttp.ReaderQuotas.MaxStringContentLength = 2147483647;      wsHttp.ReaderQuotas.MaxBytesPerRead = 6553600;      wsHttp.ReaderQuotas.MaxDepth = 6553600;      wsHttp.ReaderQuotas.MaxNameTableCharCount = 6553600;      wsHttp.CloseTimeout = new TimeSpan(0, 1, 0);      wsHttp.OpenTimeout = new TimeSpan(0, 1, 0);      wsHttp.ReceiveTimeout = new TimeSpan(0, 10, 0);      wsHttp.SendTimeout = new TimeSpan(0, 10, 0);      wsHttp.Security.Mode = SecurityMode.None;      Uri baseAddress = new Uri("http://127.0.0.1:9999/clientserver");      ServiceHost host = new ServiceHost(typeof(ClientServer), baseAddress);      ServiceMetadataBehavior smb = new ServiceMetadataBehavior();      smb.HttpGetEnabled = true;      host.Description.Behaviors.Add(smb);      ServiceBehaviorAttribute sba = host.Description.Behaviors.Find<ServiceBehaviorAttribute>();      sba.MaxItemsInObjectGraph = 2147483647;      host.AddServiceEndpoint(typeof(IClientServer), wsHttp, "");      host.Open();    }  }}

View Code

C/S程序跑起来就OK了。

三、B/S程序

程序结构如下图:

WCF的接口DataService、Web程序

DataService需要引用数据结构DataStruct和WCFServer,是C/S程序编译后的dll拿过来的,Web需要引用DataStruct,如下图:

ClientServer:

using System;using System.Collections.Generic;using System.Linq;using System.ServiceModel;using System.ServiceModel.Description;using System.Text;using System.Threading.Tasks;using DataStruct;using WCFServer;namespace DataService{  public class ClientServer  {    ChannelFactory<IClientServer> channelFactory;    IClientServer proxy;    /// <summary>    /// 创建连接客户终端WCF服务的通道    /// </summary>    public void CreateChannel()    {      string url = "http://127.0.0.1:9999/clientserver";      WSHttpBinding wsHttp = new WSHttpBinding();      wsHttp.MaxBufferPoolSize = 524288;      wsHttp.MaxReceivedMessageSize = 2147483647;      wsHttp.ReaderQuotas.MaxArrayLength = 6553600;      wsHttp.ReaderQuotas.MaxStringContentLength = 2147483647;      wsHttp.ReaderQuotas.MaxBytesPerRead = 6553600;      wsHttp.ReaderQuotas.MaxDepth = 6553600;      wsHttp.ReaderQuotas.MaxNameTableCharCount = 6553600;      wsHttp.SendTimeout = new TimeSpan(0, 10, 0);      wsHttp.Security.Mode = SecurityMode.None;      channelFactory = new ChannelFactory<IClientServer>(wsHttp, url);      foreach (OperationDescription op in channelFactory.Endpoint.Contract.Operations)      {        DataContractSerializerOperationBehavior dataContractBehavior = op.Behaviors.Find<DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior;        if (dataContractBehavior != null)        {          dataContractBehavior.MaxItemsInObjectGraph = 2147483647;        }      }    }    /// <summary>    /// 测试    /// </summary>    public TestData Test(string param)    {      proxy = channelFactory.CreateChannel();      try      {        return proxy.Test(param);      }      catch (Exception ex)      {        return null;      }      finally      {        (proxy as ICommunicationObject).Close();      }    }  }}

View Code

TestController:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using DataService;using DataStruct;namespace BSClient.Controllers{  public class TestController : Controller  {    public ActionResult Index()    {      ClientServer client = new ClientServer();      client.CreateChannel();      ViewData["data"] = client.Test("ABCD");      return View();    }  }}

View Code

Index.cshtml:

@using DataStruct;@{  ViewBag.Title = "Index";  TestData data = ViewData["data"] as TestData;  if (data == null) { data = new TestData(); }}<h2>Index</h2><h2>@data.Name</h2><h2>@data.Code</h2>

View Code

先启动C/S程序,再启动B/S程序,B/S的运行结果如下图所示:

上面以最快的速度写了一个WCF的简单的Demo,程序跑起来了,后面的再慢慢学吧。