物联网技术综合实训教程【2.0】
7. 4. 4 服务发布方法
本系统的网络服务访问接口 ( BasicGatewayService、 RestfulService、 AuthedBasicGatewayService 等) 都是通过微软的 WCF 框架发布的。 这些服务都是通过 ServiceManager 发布的。
发布代码如下: BasicGatewayService 发布/ / 服务合约的细节
/ / 这本来是不需要设置的, 但是服务传输了图像, 造成一次性传输的信息量过大, 不设置缓存长度, 会出现缓存不够长, 而导致通信错误。
WSHttpBinding NoneSecurity = new WSHttpBinding(); / / 没有安全措施的服务 NoneSecurity. Name = " NoneSecurity" ; / / binding 的名字 NoneSecurity. MaxBufferPoolSize = 2097152; / / 最大缓存池大小 NoneSecurity. MaxReceivedMessageSize = 2097152; / / 最大消息长度 NoneSecurity. UseDefaultWebProxy = false; / / 不使用代理 NoneSecurity. ReaderQuotas. MaxArrayLength = 2097152; / / 最大序列长度 NoneSecurity. ReaderQuotas. MaxStringContentLength = 2097152; / / 最大字符串 长度 NoneSecurity. Security. Mode = SecurityMode. None; / / 安全行为服务地址。 这个端口号和 IP 地址一定要和实际计算机的一致。 / / 端口号和地址定义在 GatewayInfo. xml 文件里 Uri baseAddress = new Uri ( " http:/ / " + ServiceBase. Instance. GatewayInfo. ServerAddr + " :" + ServiceBase. Instance. GatewayInfo. ServerPort + " / Gateway / " ); / / 把服务托管到 host 里, 这时的服务只是个框架, 是个容器, 里面的内容是空的。 ServiceHost host = new ServiceHost(new BasicGatewayService(),baseAddress); / / 添加服务行为 / / 设置服务的描述文件 ( wsdl 文件) , 可以通过 HTTP 方式获得 ServiceMetadataBehavior metaBehaviour = new ServiceMetadataBehavior( ) ; metaBehaviour. HttpGetEnabled = true; host. Description. Behaviors. Add( metaBehaviour) ; ServiceMetadataBehavior BasicGatewayMetaBehavior = new ServiceMetadataBehavior( ) ; BasicGatewayMetaBehavior. HttpsGetEnabled = true; / / 生成服务终结点。 这是真正的服务。 ServiceEndpoint BaseGatewayPortal = new ServiceEndpoint ( ContractDescription. GetContract( typeof( OpenService. IBasicGatewayService) ) ,NoneSecurity,new EndpointAddress ( " http: / / 115. 25. 48. 98:8902 / BasicGateway / " ) ) ; / / ServiceEndpoint GatewayPortal = new ServiceEndpoint ( ContractDescription. GetContract ( typeof ( Services. WCF. IGatewayService ) ) , NoneSecurity1,new EndpointAddress( " http: / / 115. 25. 48. 98:8902 / Gateway / " ) ) ; / / 添加服务终结点。 也就是把服务真正地添加到了 host 里 host. AddServiceEndpoint( BaseGatewayPortal) ; / / host. AddServiceEndpoint( GatewayPortal) ; / / 开启服务, 以便客户端访问 host. Open( ) ; / / 通过浏览器访问 http: / / 115. 25. 48. 98: 8902 / BasicGateway / ? wsdl, 如果看到返 回的 xml 文档, 说明服务开启成功了。