/// <summary> /// 生成远程代理对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="wcftype"></param> /// <param name="ip"></param> /// <param name="port"></param> /// <param name="mark"></param> /// <returns></returns> public T CreateRemoteObject <T>(WCFManager.WCFBindingType wcftype, string ip, int port, string mark, TimeSpan timeout, object callback = null) { var binding = WCFManager.CreateBinding(wcftype); binding.ReceiveTimeout = timeout; var url = string.Format("{0}://{1}:{2}", WCFManager.GetWcfAddressMark(wcftype), ip, port) + "/" + mark; url = url.ToLower().Trim(); if (_channelfactorys.ContainsKey(url)) { if (_channelfactorys[url].State == CommunicationState.Opened) { try { _channelfactorys[url].Close(); } catch { } } _channelfactorys.Remove(url); _channelproxys.Remove(url); } if (callback == null) { var channelFactory = new ChannelFactory <T>(binding, url); var proxy = channelFactory.CreateChannel(); _channelfactorys.Add(url, channelFactory); _channelproxys.Add(url, proxy); return(proxy); } else { var ctx = new InstanceContext(callback); var channelFactory = new DuplexChannelFactory <T>(ctx, binding, url); var proxy = channelFactory.CreateChannel(); _channelfactorys.Add(url, channelFactory); _channelproxys.Add(url, proxy); return(proxy); } }
/// <summary> /// 绑定WCF服务 /// </summary> /// <param name="objectType">对象类型</param> /// <param name="interfaceType">接口或相关类型</param> /// <param name="ipaddress">绑定IP地址</param> /// <param name="port">绑定端口</param> /// <param name="servermark">当前类型标识</param> public void StartServerBind(Type objectType, Type interfaceType, WCFManager.WCFBindingType wcftype, string ipaddress, int port, string servermark) { var serverurl = string.Format("{0}://{1}:{2}", WCFManager.GetWcfAddressMark(wcftype), ipaddress, port) + "/" + servermark; serverurl = serverurl.ToLower().Trim(); //如果已经绑定过..则直接返回 if (BindedWcfServers.ContainsKey(serverurl)) { //关闭已存在的服务 var hosttmp = BindedWcfServers[serverurl]; hosttmp.Close(); BindedWcfServers.Remove(serverurl); } ServiceHost host = new ServiceHost(objectType, new Uri(string.Format("{0}://{1}:{2}", WCFManager.GetWcfAddressMark(wcftype), ipaddress, port))); BindedWcfServers.Add(serverurl, host);//记录 host.AddServiceEndpoint(interfaceType, WCFManager.CreateBinding(wcftype), servermark); if (host.Description.Behaviors.Find <ServiceMetadataBehavior>() == null) { ServiceMetadataBehavior metadata = new ServiceMetadataBehavior(); host.Description.Behaviors.Add(metadata); } host.Open(); }