完成一个基本WCF实例,要求:
1. 使用 双工契约;
2. 使用 net.tcp 绑定方式;
3. 使用 ConsoleApplication 服务,若要使用IIS 请查阅《WCF服务使用netTcpBinding》;
1. 定义ServiceContract
定义服务端ServiceContract, ServiceContract 特性的构造方法中,指定CallbackContract 的类型
[ServiceContract(CallbackContract = typeof(IStockServiceCallback))]
public interface IStockService
{
[OperationContract]
double GetPrice(string ticker);
[OperationContract(IsOneWay = true)]
void RegisterForUpdate(string ticker);
}
public interface IStockServiceCallback
{
[OperationContract(IsOneWay = true)]
void PriceUpdate(string ticker, double price);
}
2. 实现ServiceContract
public class StockService : IStockService
{
public class Worker
{
public string ticker;
public Update workProcess;
}
public static Hashtable workers = new Hashtable();
#region IStockService Members
public double GetPrice(string ticker)
{
return 94.95;
}
public void RegisterForUpdate(string ticker)
{
Worker worker = null;
if (!workers.ContainsKey(ticker))
{
worker = new Worker();
worker.ticker = ticker;
worker.workProcess = new Update();
worker.workProcess.ticker = ticker;
workers.Add(ticker, worker);
}
worker = (Worker)workers[ticker];
IStockServiceCallback c = OperationContext.Current.GetCallbackChannel();
lock (worker.workProcess.callbacks)
{
worker.workProcess.callbacks.Add(c);
}
Thread t = new Thread(new ThreadStart(worker.workProcess.SendUpdateToClient));
t.IsBackground = true;
t.Start();
}
#endregion
}
3. 配置服务;
WCF 服务配置比较复杂,可以通过WCF Service Configuration Editor 工具进行配置,如图:
配置结果代码如下:
4. 承载服务
使用ServiceHost类进行 , 代码如下:
public static void Host(Type type)
{
using (ServiceHost servcieHost = new ServiceHost(type))
{
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
servcieHost.Description.Behaviors.Add(behavior);
servcieHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
servcieHost.Opened += delegate
{
Console.WriteLine("{0}已启动,按键终止程序,", type.FullName);
};
servcieHost.Open();
Console.ReadLine();
servcieHost.Close();
}
}
5. 生成客户端
使用svcutil.exe工具生成 config 及 Client.cs 文件,/config 指定生成配置文件,/out 指定生成Client代码文件, /async 指定生成异步处理代码执行脚本 ,:
svcutil net.tcp://localhost:809/StockService/mex /config:app.config /out:StockServiceProxy.cs /async
6. 运行程序
运行结果如下: