1
votes

I created a self hosted WCF service with netTcpBinding. I am using a WinForm based client to connect to this service. I have observed that while the client is up and running, I always lose connection to the WCF service - faulted state!.

To resolve this, I created a thread to keep the connection alive. I let the client sit and, after about a week, found an error message in my logs : TCP connection error 10061 - client was refused connection. The keep alive thread cannot recreate the connection object - the logs still display "connection refused".

In my configuration file for the service host, I have a base address but no endpoint address. MSDN says that the when no endpoint address is given, the endpoint address becomes the base address when the Open method is called.

Do I still need to give an endpoint address to resolve the "TCP connection refused" issue?

Thanks in advance for any advice.

1

1 Answers

2
votes

I think the main problem is that you're trying to always keep a connection "alive" to a WCF service. That is not the way to do it with WCF services.

In WCF, the recommended best practice is to use "per-call" activation, e.g. your client call the service, a new isolated instance of the service class is created for that request and handles it, and then it's disposed and the connection between client and server is basically gone again.

Now NetTcpBinding is special in that it has a transport-level session with the server. However, you still should

  • create the client side proxy
  • call the service
  • close the client side proxy

as a general rule.

Furthermore, if your channel is in a faulted state, that means you have .NET exceptions happening on the server-side that don't get caught and handled. In such a case, WCF goes into "panic mode" and basically invalidates the channel - the connection between the client and the server. After all, your server side code just blew up - what's the point in keeping the channel alive??

So on your server-side, you need to make sure you catch and handle all .NET exceptions, and if you want to send them back to the client, convert them to SOAP Faults (FaultException or FaultException<T>) so that they won't thrash the channel. Check out the WCF's IErrorHandler interface for that.

And on your client side, you need to build some logic to check for a faulted channel state, and if it is indeed faulted, toss it away and recreate it from scratch.

Putting all those bits into place, you should have no trouble at all with your WCF services - no hacks like background threads to "keep alive" a connection needed.