public WcfClientFactory(string name) { DefaultConnections = 10; Binding = new NetTcpBinding(); Binding.CloseTimeout = new TimeSpan(0, 0, 1); Binding.Security = new NetTcpSecurity { Mode = SecurityMode.None }; Binding.MaxReceivedMessageSize = 1024 * 1024 * 10; Binding.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas { MaxStringContentLength = 1024 * 1024 * 10 }; ClientFactorySelection selecton = (ClientFactorySelection)System.Configuration.ConfigurationManager.GetSection(name); if (selecton == null) { throw CN100WcfException.CONFIG_NOTFOUND(name); } foreach (ConnectionElement item in selecton.Connections) { Connections.Add(new ConnectItem { IPAddress = item.IP, Port = int.Parse(item.Port) }); } }
/// <summary> /// 获取一个服务连接,使用方式始下 /// <example> /// <code> /// using (WcfTcpClient<IUserService> Client = WcfClientFactory.CreateClient<IUserService>()) /// { /// User user = Client.Channel.GetUser("henry"); /// } /// </code> /// </example> /// </summary> /// <typeparam name="T">服务接口</typeparam> /// <returns>WcfTcpClient<T> </returns> public WcfTcpClient <T> CreateClient <T>() { IWcfTcpClientPool pool = null; lock (mClientPools) { Type type = typeof(T); if (!mClientPools.TryGetValue(type, out pool)) { ServiceContractAttribute[] scs = (ServiceContractAttribute[])type.GetCustomAttributes(typeof(ServiceContractAttribute), false); if (scs == null || scs.Length == 0) { throw CN100WcfException.SERVER_CONTRACT_NOFOUND(); } string name; if (string.IsNullOrEmpty(scs[0].Name)) { name = type.Name; } else { name = scs[0].Name; } string[] address = new string[Connections.Count]; for (int i = 0; i < Connections.Count; i++) { address[i] = string.Format(BASEADDRESS, Connections[i].IPAddress, Connections[i].Port, name); } pool = new WcfTcpClientPool <T>(Binding, DefaultConnections, address); mClientPools.Add(type, pool); } } WcfTcpClient <T> client = (WcfTcpClient <T>)pool.GetClient(); if (client == null) { throw new Exception("Connection is not available!"); } TimeSpan dt = DateTime.Now - client.ActiveTime; while (dt.TotalMinutes > 5) { client = (WcfTcpClient <T>)pool.GetClient(); if (client == null) { throw new Exception("Connection is not available!"); } dt = DateTime.Now - client.ActiveTime; } client.ActiveTime = DateTime.Now; return(client); }