1. 程式人生 > >無廢話WCF入門教程五[WCF的通訊模式]

無廢話WCF入門教程五[WCF的通訊模式]

1 //配置檔案中的 binding 指定 2 <endpoint address="" binding="wsDualHttpBinding" contract="WCFService_DualPlex.IUser"></endpoint> 3 4 //服務端介面 5 using System.ServiceModel; 6 7 namespace WCFService_DualPlex 8 { 9 [ServiceContract(CallbackContract = typeof(IUserCallback))] 10 public
interface IUser 11 { 12 [OperationContract] 13 string ShowName(string name); 14 } 15 16 public interface IUserCallback 17 { 18 [OperationContract(IsOneWay = true)] 19 void PrintSomething(string str); 20 } 21 } 22 23 //服務端實現 24 using System.ServiceModel;
25 26 namespace WCFService_DualPlex 27 { 28 public class User : IUser 29 { 30 IUserCallback callback = null; 31 32 public User() 33 { 34 callback = OperationContext.Current.GetCallbackChannel<IUserCallback>(); 35 } 36 37 public
string ShowName(string name) 38 { 39 //在伺服器端定義字串,呼叫客戶端的方法向客戶端列印 40 string str = "伺服器呼叫客戶端..."; 41 callback.PrintSomething(str); 42 //返回服務端方法 43 return "WCF服務,顯示名稱:" + name; 44 } 45 } 46 } 47 48 //客戶端呼叫 49 using System; 50 using System.ServiceModel; 51 using WCFClient_DualPlex.WCFService_DualPlex; 52 53 namespace WCFClient_DualPlex 54 { 55 //實現服務端的回撥介面 56 public class CallbackHandler : IUserCallback 57 { 58 public void PrintSomething(string str) 59 { 60 Console.WriteLine(str); 61 } 62 } 63 64 class Program 65 { 66 static void Main(string[] args) 67 { 68 InstanceContext instanceContext = new InstanceContext(new CallbackHandler()); 69 UserClient client = new UserClient(instanceContext); 70 Console.WriteLine(DateTime.Now); 71 string result = client.ShowName("李林峰"); 72 Console.WriteLine(result); 73 Console.WriteLine(DateTime.Now); 74 Console.ReadLine(); 75 } 76 } 77 }