• WCF快速上手(二)


    服务端是CS程序,客户端(调用者)是BS程序

    一、代码结构:

    二、服务接口Contract和实体类Domain

    INoticeService:

    using Domain;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.ServiceModel;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Contract
    {
        /// <summary>
        /// 通知公告
        /// </summary>
        [ServiceContract]
        public interface INoticeService
        {
            /// <summary>
            /// 获取一条公告信息
            /// </summary>
            [OperationContract]
            Notice GetNotice();
        }
    }
    View Code

    Notice:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Domain
    {
        /// <summary>
        /// 通知公告
        /// </summary>
        public class Notice
        {
            /// <summary>
            /// 标题
            /// </summary>
            public string Title { get; set; }
            /// <summary>
            /// 内容
            /// </summary>
            public string Content { get; set; }
            /// <summary>
            /// 数据
            /// </summary>
            public byte[] Data { get; set; }
        }
    }
    View Code

    三、服务WcfService和宿主WcfHost

    NoticeService:

    using Contract;
    using Domain;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace WcfService
    {
        /// <summary>
        /// 通知公告服务
        /// </summary>
        public class NoticeService : INoticeService
        {
            /// <summary>
            /// 获取一条公告信息
            /// </summary>
            public Notice GetNotice()
            {
                Notice notice = new Notice();
                notice.Title = "测试标题";
                notice.Content = "测试内容";
                notice.Data = new byte[200000];
                for (int i = 0; i < 200000; i++)
                {
                    notice.Data[i] = (byte)100;
                }
                return notice;
            }
        }
    }
    View Code

    Program:

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.IO;
    using System.Linq;
    using System.ServiceModel;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using WcfService;
    
    namespace WcfServer
    {
        class Program
        {
            static void Main(string[] args)
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + "Service";
                string[] fileArr = Directory.GetFiles(path);
                int port = int.Parse(ConfigurationManager.AppSettings["ServerPort"]);
    
                foreach (string fileName in fileArr)
                {
                    string url = string.Format("http://localhost:{0}/Service/{1}", port, Path.GetFileName(fileName));
                    Uri[] uri = new Uri[] { new Uri(url) };
    
                    ServiceHost host = new ServiceHost(typeof(NoticeService), uri);
                    host.Open();
                }
    
                Console.WriteLine("服务成功启动");
                Console.Read();
            }
        }
    }
    View Code

    服务端App.config配置:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
      </startup>
      <appSettings>
        <add key="ServerPort" value="8998"/>
      </appSettings>
      <system.serviceModel>
        <services>
          <service name="WcfService.NoticeService" behaviorConfiguration="ServiceBehavior" >
            <endpoint  contract="Contract.INoticeService" address="" binding="basicHttpBinding" bindingConfiguration="ServiceBinding">
              <identity>
                <dns value="localhost" />
              </identity>
            </endpoint>
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
          </service>
        </services>
        <bindings>
          <basicHttpBinding>
            <binding name="ServiceBinding" sendTimeout="00:00:20" maxReceivedMessageSize="2147483646">
            </binding>
          </basicHttpBinding>
        </bindings>
        <behaviors>
          <serviceBehaviors>
            <behavior name="ServiceBehavior">
              <serviceMetadata httpGetEnabled="true"/>
            </behavior>
          </serviceBehaviors>
        </behaviors>
      </system.serviceModel>
    </configuration>
    View Code

    四、客户端

    NoticeProxy:

    using Contract;
    using Domain;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.ServiceModel;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace WcfClient
    {
        /// <summary>
        /// 通知公告
        /// </summary>
        public class NoticeProxy : INoticeService
        {
            private ChannelFactory<INoticeService> channelFactory;
            private INoticeService server;
    
            public NoticeProxy()
            {
                channelFactory = new ChannelFactory<INoticeService>("NoticeService");
                server = channelFactory.CreateChannel();
            }
    
            /// <summary>
            /// 获取一条公告信息
            /// </summary>
            public Notice GetNotice()
            {
                return server.GetNotice();
            }
        }
    }
    View Code

    客户端调用服务:

    using Domain;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using WcfClient;
    
    namespace WinformClient
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void btnTest_Click(object sender, EventArgs e)
            {
                try
                {
                    NoticeProxy proxy = new NoticeProxy();
                    Notice notice = proxy.GetNotice();
                    MessageBox.Show(notice.Data.Length.ToString());
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
    }
    View Code

    客户端App.config配置:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
      </startup>
      <system.serviceModel>
        <behaviors>
          <endpointBehaviors>
            <behavior name="ServiceBehavior">
              <dataContractSerializer maxItemsInObjectGraph="2147483646"/>
            </behavior>
          </endpointBehaviors>
        </behaviors>
        <bindings>
          <basicHttpBinding>
            <binding name="ServiceBinding"  maxReceivedMessageSize="2147483646">
              <readerQuotas maxArrayLength="65242880" maxStringContentLength="65242880"/>
            </binding>
          </basicHttpBinding>
        </bindings>
        <client>
          <endpoint name="NoticeService" contract="Contract.INoticeService"  address="http://localhost:8998/Service/NoticeService.svc" behaviorConfiguration="ServiceBehavior"  binding="basicHttpBinding" bindingConfiguration="ServiceBinding" />
        </client>
      </system.serviceModel>
    </configuration>
    View Code
  • 相关阅读:
    Python获取当前 年 月 日
    HTML5手机应用的最大优势就是可以在网页上直接调试和修改
    使用PostSharp在.NET平台上实现AOP
    HTML5的设计目的是为了在移动设备上支持多媒体
    中法两国还将在中非、东非携手加强基础设施建设、安全、金融、能源、维和护航、医药卫生和教育培训等领域全面展开合作
    中国“互联网+”战略与欧洲单一数字市场建设、欧洲智慧城市建设等项目
    全球价值链的分工,‘国际产能合作’将带动全球产业链的调整
    中国在全球经济格局以及产业链条上的地位已今非昔比
    Bitmap Image Graphics
    C#利用WebClient 两种方式下载文件
  • 原文地址:https://www.cnblogs.com/s0611163/p/7239012.html
Copyright © 2020-2023  润新知