這是具有自託管服務和客戶端的準系統示例。
合同
[ServiceContract(CallbackContract = typeof(IService1Callback), SessionMode=SessionMode.Required)]
public interface IService1
{
[OperationContract]
void Process(string what);
}
public interface IService1Callback
{
[OperationContract]
void Progress(string what, decimal percentDone);
}
服務器
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
public class Service1 : IService1
{
public void Process(string what)
{
Console.WriteLine("I'm processing {0}", what);
for (int i = 0; i < 10; i++)
{
OperationContext.Current.GetCallbackChannel<IService1Callback>().Progress(what, (i+1)*0.1M);
}
}
}
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(Service1), new Uri[] { new Uri("net.tcp://localhost:6789") }))
{
host.AddServiceEndpoint(typeof(IService1), new NetTcpBinding(SecurityMode.None), "Service1");
host.Open();
Console.ReadLine();
host.Close();
}
}
}
客戶
public class CallbackHandler : IService1Callback
{
public void Progress(string what, decimal percentDone)
{
Console.WriteLine("Have done {0:0%} of {1}", percentDone, what);
}
}
class Program
{
static void Main(string[] args)
{
// Setup the client
var callbacks = new CallbackHandler();
var endpoint = new EndpointAddress(new Uri("net.tcp://localhost:6789/Service1"));
using (var factory = new DuplexChannelFactory<IService1>(callbacks, new NetTcpBinding(SecurityMode.None), endpoint))
{
var client = factory.CreateChannel();
client.Process("JOB1");
Console.ReadLine();
factory.Close();
}
}
}
這使用一個雙工信道OV er net.tcp,通信由服務器觸發以通知客戶進程更新。
客戶端會顯示:
Have done 10% of JOB1
Have done 20% of JOB1
Have done 30% of JOB1
Have done 40% of JOB1
Have done 50% of JOB1
Have done 60% of JOB1
Have done 70% of JOB1
Have done 80% of JOB1
Have done 90% of JOB1
Have done 100% of JOB1
肯定看一看由GertArnold – EtherDragon