Alex Rivera | Logout

WCF TCP clients - basic guidelines on how to use them?

Asked 2011-06-02T18:39:23.727
10

I've got a WCF service and want to connect to it using a TCP binding. This is all well and good, but how are you supposed to handle the clients? I've noticed that if you create a new client for each call it doesn't re-use the channel and leaves around a bunch of TCP connections until they time out.

Is it normal use to create a client, call a method on it, then close it?

What if you want to re-use the connection? What are the limitations on that? Can you make simultaneous calls from different threads? If you can't, do you have to do your own connection pooling? And when re-using the connection, do you have to check the connection state before making calls and clean it up if it's faulted?

Edit
Report

1 Answer

17

Well this is a lot of questions together and the situation is really little bit complicated. When you create a client you can do it either via service reference and get class derived from ClientBase<ServiceContract> or you can use ChannelFactory<ServiceContract> and create channels manually (the former case uses the ChannelFactory internally).

How this relates to your question? Lets first look at real TCP connection. When you define NetTcpBinding you can set its MaxConnections property (default is 10). This property defines the number of pooled connection. It means that if you create client channel to the server and close the channel the connection is not terminated immediately. It remains opened in the pool until it is used by another opened client channel to the same server or until its idle timeout expires. You can open as many connections as the server allows you but only number defined by MaxConnections will be pooled once you close related client channels. Other connections will be terminated immediately. If you create CustomBinding you can use TCP transport directly where you can also control idle timeout (I think default is 2 minutes). Connections are pooled as long as the related ChannelFactory is not destroyed = use one ChannelFactory per application (ClientBase do it internally).

Now lets talk about channel itself because it is related to your other questions. WCF differs sessionfull and sessionless channels. TcpTransportChannel is sessionfull. It means that once you open the channel you create a session. Session means that all requests from the single client proxy are by default always served by the same service instance (per session instancing). But the instance is by default single threaded. It means that you can have multiple threads using the same proxy but the service will handle requests i

answered 2011-06-02T19:13:26.427

Your Answer