zoukankan      html  css  js  c++  java
  • WCF框架基础(二)

    WCF协定以及服务逻辑实现之后,如果客户端能够对其进行调用,则需要将上文的服务协定运行起来,运行服务协定需要创建服务终结点、地址、激活元数据交换、以及最终的服务启动和停止功能

    1.创建基本地址和服务主机

     Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");//创建基本地址
     ServiceHost selfHost = new ServiceHost(typeof(CalculatorService),baseAddress);//创建服务主机

    2.添加服务终结点

     selfHost.AddServiceEndpoint(typeof(IService), new WSHttpBinding(), "CalculatorService");//参数分别为接口类型、传输协议、服务名称

    3.启动元数据交换

             ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
             smb.HttpGetEnabled = true;//启用HttpGet
             selfHost.Description.Behaviors.Add(smb);//添加元数据

    4.启动和终止WCF服务

              selfHost.Open();
              Console.WriteLine("服务已启动.");
              Console.WriteLine("按Enter终止服务.");
              Console.WriteLine();
              Console.ReadLine();
              selfHost.Close();

    至此服务就能运行起来 完整代码如下

      static void Main(string[] args)
            {
                Uri baseAddress = new Uri("http://localhost:8000/ServiceModelSamples/Service");
                ServiceHost selfHost = new ServiceHost(typeof(CalculatorService),baseAddress);
                try
                {
                    selfHost.AddServiceEndpoint(typeof(IService), new WSHttpBinding(), "CalculatorService");
                    ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                    smb.HttpGetEnabled = true;
                    selfHost.Description.Behaviors.Add(smb);
                    selfHost.Open();
                    Console.WriteLine("服务已启动.");
                    Console.WriteLine("按Enter终止服务.");
                    Console.WriteLine();
                    Console.ReadLine();
                    selfHost.Close();
                }
                catch(CommunicationException e)
                {
                    Console.WriteLine("异常:{0}",e.Message);
                    selfHost.Abort();
                }
            }

    在WCF客户端创建和调用时 必需保持该服务在启动状态

  • 相关阅读:
    Jquery消息提示插件toastr使用详解
    spingboot jar 包启动遇到得坑
    freemarker使用shiro标签(spring boot)
    sping boot 集成shiro
    java 线程安全(初级)
    java GC jvm 内存分布 和新生代,老年代,永久代,(详细)
    java的新生代 老年代 永久代
    windows下rabbitmq(架构师必备神器)集群搭建
    友盟移动开发平台.NET版本SDK
    jstree无限级菜单ajax按需动态加载子节点
  • 原文地址:https://www.cnblogs.com/akingyao/p/2673293.html
Copyright © 2011-2022 走看看