Wcf – How to a WCF Service Raise Events to its Clients

wcf

I want to know is there way of Event Handling in WCF.
I came across Callbacks in WCF, but i want to do Event Handling in WCF.

My requirement is like i want to raise event to particular clients not to all the clients using Event Handling in WCF and i also want to maintain session.

I have seen Publisher/Subscriber model in WCF which deals with Callback , but this model publish to all the clients who have subscribed but i want to publish only to selected clients.

I think that can be done using Events in WCF.

Client side :

public class Callbacks : IServiceCallback
{
    public void CallToMyClient(string name)
    {
        this.CallToMyClient(name);  

    }
}

protected void Page_Load(object sender, EventArgs e)
{
    Callbacks callback = new Callbacks();            
    ServiceClient client = new ServiceClient(new InstanceContext(callback));        

    client.SubscribeClient();
    client.DoSomeWork(); 
}

Best Answer

There is no Event in WCF to notify it's client but there is a callback channel, the purpose of the callback channel is same as event though the working principle is totally different in both cases. To notify a particular client what you could do is store callback channel of that client while subscribing to somewhere, (I prefer Dictionary in this case). Later you can pick the instance and invoke your callback method over that channel, doing so only one client will get notified.

UPDATE

If you are interested here is the code:

public interface IClientCallback
{
    //Your callback method
    [OperationContract(IsOneWay = true)]
    void CallToMyClient(string name);
}
[ServiceContract(CallbackContract = typeof(IClientCallback))]
public interface ITestService
{

    [OperationContract(IsOneWay = true)]
    void SubscribeClient();
    [OperationContract(IsOneWay = true)]
    void DoSomeWork();
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Reentrant)]
public class ServiceImplementation : ITestService
{
    private static readonly List<IClientCallback> CallbackChannels = new List<IClientCallback>();

    /// <summary>
    /// client should call this method before being notified to some event
    /// </summary>
    public void SubscribeClient()
    {
        var channel = OperationContext.Current.GetCallbackChannel<IClientCallback>();
        if (!CallbackChannels.Contains(channel)) //if CallbackChannels not contain current one.
        {
            CallbackChannels.Add(channel);
        }
    }

    public void DoSomeWork()
    {
        //Here write your code to do some actual work
        //After you done with your work notify client
        //here you are calling only the first client that is registered
        IClientCallback callbackChannel = CallbackChannels[0];
        callbackChannel.CallToMyClient("You are the only one receving this message");
    }
}
Related Topic