是的,你可以實現推送功能從服務器到客戶端。您只需通過使用WCF服務存儲每個客戶端的實例上下文對象並調用將在客戶端實現的回調方法來維護服務器中的連接客戶端列表。所以所有的客戶端都會通過回調方法進行更新。
可以存儲客戶端的情況下上下文對象像下面,在客戶名單是哈希表:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class HostService : IHostService
{
public bool Connect(Guid applicationId)
{
if (!ClientList.ContainsKey(applicationId))
{
IHostServiceCallback client = OperationContext.Current.GetCallbackChannel<IHostServiceCallback>();
ClientList.Add(applicationId, client);
}
}
接口的主機服務:
[ServiceContract]
public partial interface IHostServiceCallback
{
[OperationContract(IsOneWay = true)]
void SendNotification(string message);
}
:服務
[ServiceContract(CallbackContract = typeof(IHostServiceCallback), SessionMode = SessionMode.Required)]
public partial interface IHostService
{
[OperationContract]
bool Connect(Guid applicationId);
}
回調類
當您的服務器在任何事件處理程序中收到通知時,將其發送給所有客戶端li柯:
private void Notification_Received(object sender, EventReceivedEventArgs e)
{
foreach (IHostServiceCallback client in ClientList.Values)
{
try
{
client.SendNotification(notificationMessage);
}
catch
{
}
}
}
在客戶端應用程序,您已經實現回調方法,如:
public partial class Window1 : Window, IHostServiceCallback
{
public void SendNotification(string message)
{
// do some operation
}
}