Jason Kleban
Jason Kleban

Reputation: 20788

WCF Server-to-Client callback method with return value

I've attempted the question different ways, check my profile for the other two questions explaining the difficulty I've had with the approaches I've taken to this scenario. I'll skip them here.

I just need an example (C# preferred) of a server calling back to a client (over a nettcp channel), the client calculates an answer, and returns a result.

Thanks!

Upvotes: 2

Views: 11589

Answers (1)

VinayC
VinayC

Reputation: 49195

Check this article on CodeProject. This describes basic example of callbacks. Few things that you may have to change:

  • On callback contract, operations marked as one way - this is to avoid blocking of server due to bad client (a recommended practice). But if you must block the server then you need to remove one way. Note that if you are going to callback multiple clients one by one then you may have to callback each one on different thread other wise first client will block callback to next client.

  • When to invoke callback is really a server implementation. The given example maintains a list of client callback channels whenever client joins (or subscribes in your requirement). Now this list can be used to invoke callback in any way you want. So you can invoke callbacks on timer by simply iterating over the list. Note that you have to ensure thread-safe access to the list.

  • If client has to return some result in callback then again OneWay cannot be used.

  • As mentioned earlier, subscribe means simply adding to the list (join party in example) and unsubscribe means removing from the list (leave party).

Edit:

I have taken the source code from the example sighted and modified it as follows:

Added a method Echo in callback contract:

public interface IBeerInventoryCallback
{
   ...

    [OperationContract]
    string Echo(string message);
}

Invoked Echo from service when someone left the party and printed response from client on console. And it worked w/o any issues.

Note that this example uses VS generated client proxy that inherits from System.ServiceModel.DuplexClientBase<T> which makes client code much simpler. Perhaps, you should try it.

Upvotes: 3

Related Questions