我想知道这是否是一个已知的错误。
我的代码与Dave略有不同,而他的ServiceHost实例(名为WebService)不在Start()方法中。我的ServiceHost实例(命名主机)在里面声明。在调试时,我在主机描述中检查端点的地址已更改为正确的IP。但是,Open()仍然会使用旧的错误IP地址抛出异常。
private bool InitHost(PtiType type, string serverIp, int portNumber)
{
if (!HostDictionary.ContainsKey(type))
{
Uri addressBase = new Uri(String.Format("net.tcp://{0}:{1}/CommunicationService/{2}", serverIp, portNumber.ToString(), type.ToString()));
var service = new PtiCommunicationService(type);
service.ClientConnected += service_ClientConnected;
service.ClientBroadcasted += service_ClientBroadcasted;
service.ClientSentTo += service_ClientSentTo;
service.ClientDisconnected += service_ClientDisconnected;
var host = new ServiceHost(service, addressBase);
//For publishing metadata only
//Define Metadata endPoint, So we can publish information about the service
ServiceMetadataBehavior mBehave = new ServiceMetadataBehavior();
host.Description.Behaviors.Add(mBehave);
//Enable debug info in fault
((ServiceDebugBehavior)host.Description.Behaviors[typeof(ServiceDebugBehavior)]).IncludeExceptionDetailInFaults=true;
host.AddServiceEndpoint(typeof(IPtiCommunication), new NetTcpBinding(SecurityMode.None), "");
host.AddServiceEndpoint(typeof(IMetadataExchange),
MetadataExchangeBindings.CreateMexTcpBinding(),
"mex");
try
{
host.Open();
//Add host to dictionary to keep track
HostDictionary.Add(type, host);
LogList.Add(String.Format("{0}\tThe service {1} at {2} is ready", DateTime.Now.ToLongTimeString(), service.ServiceType.ToString(), serverIp));
string hostInfo = String.Format("{0}\tHost information:\n", DateTime.Now.ToLongTimeString());
hostInfo += "Enpoints details:\n";
foreach (var endpt in host.Description.Endpoints)
{
hostInfo += String.Format("\t Name:\t\t{0}\n", endpt.Name);
hostInfo += String.Format("\t Logical address:\t{0}\n", endpt.Address);
hostInfo += String.Format("\t Physical address:\t{0}\n", endpt.ListenUri);
hostInfo += String.Format("\t Binding:\t\t{0}\n", endpt.Binding);
hostInfo += String.Format("\t Contract:\t{0}\n\n", endpt.Contract.ContractType.Name);
}
LogList.Add(hostInfo);
}
catch (Exception e)
{
host.Abort();
host = null;
LogList.Add(String.Format("{0}\t{1}", DateTime.Now.ToLongTimeString(), e.Message));
}
return true;
}
return false;
}
这是我的PtiCommunicationService的ServiceBehavior
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
ConcurrencyMode = ConcurrencyMode.Multiple, UseSynchronizationContext = false)]
接口的和ServiceContract
[ServiceContract(CallbackContract = typeof(IPtiCommunicationCallback), SessionMode = SessionMode.Required)]
app.config中没有其他配置。所有都在代码中。
由于
更新:
我发现我们都为ServiceHost构造函数(Object,Uri [])使用相同的重载,它构成了Web服务的单例。
当我们使用相同的单例创建新的服务主机时,以某种方式更改端点地址不会生效,因为即使主机已中止,服务实例仍然存在。
在我们创建新主机时,是否有任何解决方案来清理该单例?
到目前为止,这是我的怀疑,如果我错了,请纠正我。
答案 0 :(得分:0)
显然WCF缓存了一些套接字信息。我发现最好的解决方法是Ivan在这里https://stackoverflow.com/a/6839265/955400给出的。在尝试调用host.Open()之前,请检查是否可以打开连接。