1、根据需求建立一个类库,这里命名为ComputeServe
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace ComputeServe
{
[ServiceContract]
public interface ICompute
{
[OperationContract]
double AddData(double x, double y);
}
}
上面需要添加引用System.ServiceModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ComputeServe
{
public class Compute : ICompute
{
public double AddData(double x, double y)
{
return x + y;
}
}
}
将类库生成dll
2、建立服务端
添加刚生成的dll和System.ServiceModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace wcf1
{
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(ComputeServe.Compute)))
{
//定义绑定
System.ServiceModel.Channels.Binding httpBinding = new BasicHttpBinding();
//定义终结点
host.AddServiceEndpoint(typeof(ComputeServe.ICompute), httpBinding, "http://localhost:8001/");//所以服务端的URI也应该用这个
if (host.Description.Behaviors.Find<System.ServiceModel.Description.ServiceMetadataBehavior>() == null)
{
host.Opened += delegate
{
Console.WriteLine("Service is already open");
};
//运行
host.Open();
Console.ReadKey();
//关闭
host.Close();
}
}
}
}
}
3、客户端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace ComputeClient
{
[ServiceContract]
interface ICompute
{
[OperationContract]
double AddData(double x, double y);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace ComputeClient
{
class Compute:System.ServiceModel.ClientBase<ICompute>,ICompute
{
public double AddData(double x, double y)
{
return base.Channel.AddData(x, y);
}
}
}
注:取名ICompute,Compute这个是因为dll里面是这样命名的
调用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
namespace ComputeClient
{
class Program
{
static void Main(string[] args)
{
string address = "http://localhost:8001/";
ChannelFactory<ICompute> channel =
new ChannelFactory<ICompute>(
new BasicHttpBinding(),
new EndpointAddress(
new Uri(address)));
ICompute proxy = channel.CreateChannel();
Console.WriteLine("WCF调用结果为:{0}", proxy.AddData(2, 3));
Console.ReadKey();
}
}
}