Search code examples
c#wcftcpduplex-channel

WCF service Cannot catch a client's crash


I've created a WCF service which uses a NetTCP binding.

My service is accessed by a client, saves its callback channel and uses it to call the client later on (it's a persistent tcp connection). Everything works fine, but if I decide to suddenly kill the client - I get a SocketException which I can't catch ("An existing connection was forcibly closed by the remote host").

What have I already tried?

  1. I've added try-catch clauses in every method using the callback channel, and even in the upper level - the WCFHost which starts my service.

  2. I've tried getting both the channel and the callback channel and adding a method treating the channel faulted event:

    var channel = OperationContext.Current.Channel; 
    channel.Faulted += ChannelFaulted;
    var callbackChannel = OperationContext.Current.GetCallbackChannel<CallbackInterface>();
    var comObj = callbackChannel as ICommunicationObject;
    comObj.Faulted += ChannelFaulted;
    

In short, I'm trying to handle exceptions thrown by the client - on the server side.


Solution

  • After much investigation it turns out that a server can detect exceptions thrown by the client using the Faulted event I mentioned earlier in my question (I should have been more patient when debugging, and wait until the exception "climbed" all levels until getting to my code).

    Please note, however, that the event catches the exception only when it is too late: the channel is already null (and so is the OperationContext.Current). I couldn't catch the original SocketException thrown by the System.ServiceModel.dll even when I tried using the IServiceBehavior and the IEndpointBehavior (which set an IChannelInitializer). When my ChannelFaulted() method was finally called, there was no way to detect which client failed.