zoukankan      html  css  js  c++  java
  • WCF 客户端调用服务的方法

    本节的主要内容:1、通过代理类的方式调用服务操作。2、通过通道的方式调用服务操作。3、代码下载

    一、通过代理类的方式调用服务操作(两种方式添加代理类)

    1.手动编写代理类,如下:

    客户端契约:

    View Code
    复制代码
     1 using System;
    2 using System.Collections.Generic;
    3 using System.Linq;
    4 using System.Text;
    5
    6 using System.ServiceModel;
    7 namespace y.WcfFirst.Client.Proxys
    8 {
    9 [ServiceContract]
    10 public interface IHello
    11 {
    12 [OperationContract]
    13 string Say(string name);
    14 }
    15 }
    复制代码

    客户端代理类:

    View Code
    复制代码
     1 using System;
    2 using System.Collections.Generic;
    3 using System.Linq;
    4 using System.Text;
    5
    6 using System.ServiceModel;
    7 using System.ServiceModel.Channels;
    8 namespace y.WcfFirst.Client.Proxys
    9 {
    10 public class HelloProxy:ClientBase<IHello>,IHello
    11 {
    12 public HelloProxy()
    13 : base()
    14 {
    15 }
    16
    17 public string Say(string name)
    18 {
    19 return base.Channel.Say(name);
    20 }
    21 }
    22 }
    复制代码

    客户端app.config文件:

    按 Ctrl+C 复制代码
    按 Ctrl+C 复制代码

    客户端的调用:

    View Code
    1 using (HelloProxy proxy = new HelloProxy())
    2 {
    3 Console.WriteLine("Recevie from Server:{0}", proxy.Say(name));
    4 proxy.Close();
    5 }

    2.通过Metadata方式产生代理类。

    服务端需要对app.config进行配置如下:

    客户端的操作步骤:先运行服务端(host)。

    a.在客户端点击Add Service Reference按钮,添加Service引用。如下图:

    b.输入Address地址:http://localhost:8888,点击"GO",获取服务操作。并且重命名Namespace,如下图:

    c.客户端对代理类的调用。

    View Code

    二、通过通道方式调用服务操作

    1.客户端契约,如下:

    View Code
    复制代码
     1 using System;
    2 using System.Collections.Generic;
    3 using System.Linq;
    4 using System.Text;
    5
    6 using System.ServiceModel;
    7 namespace y.WcfFirst.ClientChannel.Proxy
    8 {
    9 [ServiceContract]
    10 public interface IHello
    11 {
    12 [OperationContract]
    13 string Say(string name);
    14 }
    15 }
    复制代码

    2.客户端配置文件的设置:如下:

    View Code
    复制代码
     1 <?xml version="1.0" encoding="utf-8" ?>
    2 <configuration>
    3 <system.serviceModel>
    4 <client>
    5 <endpoint name="wcfFirst"
    6 address="net.tcp://localhost:6666/hello"
    7 binding="netTcpBinding"
    8 contract="y.WcfFirst.ClientChannel.Proxy.IHello"></endpoint>
    9 </client>
    10 </system.serviceModel>
    11 </configuration>
    复制代码

    3.客户端调用服务操作:如下:

    View Code
    复制代码
    1 ChannelFactory<IHello> factory = new ChannelFactory<IHello>("wcfFirst");
    2 IHello channelProxy = factory.CreateChannel();
    3 using(channelProxy as IDisposable)
    4 {
    5 Console.WriteLine("Recevie from Server:{0}", channelProxy.Say(name));
    6 }
    复制代码
  • 相关阅读:
    Evanyou Blog 彩带
    Evanyou Blog 彩带
    复合类型的声明——是int *p还是int* p
    指针
    引用
    变量声明和变量定义
    C++内置类型如何存放于计算机内存中
    C++的几种字符类型
    第四章 表达式
    ++i && i++
  • 原文地址:https://www.cnblogs.com/doosmile/p/2694015.html
Copyright © 2011-2022 走看看