WCF自寄宿自调用

namespace Client
{
    class CalculateClient:System.ServiceModel.ClientBase<ICalculate>,ICalculate
    {

        public CalculateClient(Binding binding, EndpointAddress endPointAddress)
            : base(binding, endPointAddress)
        { 
        
        }

        #region ICalculate 成员

        public string Add(int a, int b)
        {
            return base.Channel.Add(a, b);
        }

        #endregion
    }
}

 

Server端

namespace Server
{
    public class Calculate:ICalculate
    {
        #region ICalculate 成员

        public string Add(int a, int b)
        {
            return (a+b).ToString();
        }

        #endregion
    }
}
namespace Server
{
    [ServiceContract]
    public interface ICalculate
    {
        [OperationContract]
        string Add(int a, int b);
    }
}

ServerHost

 class Program
    {
        static void Main(string[] args)
        {
            Uri[] baseAddres = new Uri[]{new Uri("http://10.1.28.79:8880"),new Uri("net.tcp://10.1.28.79:8881")};
            using (ServiceHost host = new ServiceHost(typeof(Calculate),baseAddres))
            {
                try
                {
                    host.AddServiceEndpoint(typeof(ICalculate), new BasicHttpBinding(), "");
                    host.AddServiceEndpoint(typeof(ICalculate), new NetTcpBinding(), "");
                    host.Open();
                    Console.WriteLine("");
                    Console.ReadKey();
                }
                catch (Exception ex)
                {
                    host.Abort();
                }
                finally
                {
                    host.Close();
                }
                
            }
        }
    }

Client

namespace Client
{
    [ServiceContract]
    public interface ICalculate
    {
        [OperationContract]
        string Add(int a, int b);
    }
}


Program

class Program
    {
        static void Main(string[] args)
        {
            BasicHttpBinding binding = new BasicHttpBinding();
            EndpointAddress address = new EndpointAddress("http://10.1.28.79:8880");
            CalculateClient client = new CalculateClient(binding, address);
            string result = client.Add(1, 20);
            Console.WriteLine("result:" + result);
            Console.Read();
        }
    }

 CalculateClient

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.ServiceModel;
using System.ServiceModel.Channels;

namespace Client
{
    class CalculateClient:System.ServiceModel.ClientBase<ICalculate>,ICalculate
    {

        public CalculateClient(Binding binding, EndpointAddress endPointAddress)
            : base(binding, endPointAddress)
        { 
        
        }

        #region ICalculate 成员

        public string Add(int a, int b)
        {
            return base.Channel.Add(a, b);
        }

        #endregion
    }
}

 

posted @ 2013-11-30 09:43  feidaochuanqing  阅读(232)  评论(0编辑  收藏  举报