Mel*_*een 9 wcf wcf-binding net.tcp
我遇到了一个问题.我在WCF有点新,所以任何帮助都会有很大的帮助.
这是我的代码:
public static void StartHosts()
{
try
{
// Create a new host
ServiceHost host = new ServiceHost(typeof(ServerTasks));
List<IPAddress> ips = new List<IPAddress>(Dns.GetHostAddresses(Dns.GetHostName()));
if (IPAddress.Loopback != null)
ips.Add(IPAddress.Loopback);
ips.RemoveAll(i => i.AddressFamily != AddressFamily.InterNetwork);
foreach (var ip in ips)
{
string uri = string.Empty;
// Formulate the uri for this host
uri = string.Format(
"net.tcp://{0}:{1}/ServerTasks",
ip.ToString(),
ServerSettings.Instance.TCPListeningPort
);
// Add the endpoint binding
host.AddServiceEndpoint(
typeof(ServerTasks),
new NetTcpBinding(SecurityMode.Transport) { TransferMode = TransferMode.Streamed },
uri
);
}
// Add the meta data publishing
var smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (smb == null)
smb = new ServiceMetadataBehavior();
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
host.Description.Behaviors.Add(smb);
host.AddServiceEndpoint(
ServiceMetadataBehavior.MexContractName,
MetadataExchangeBindings.CreateMexTcpBinding(),
"net.tcp://localhost/ServerTasks/mex"
);
// Run the host
host.Open();
}
catch (Exception exc)
{
DebugLogger.WriteException(exc);
}
}
Run Code Online (Sandbox Code Playgroud)
行抛出异常:'host.Open();'
例外是:
System.InvalidOperationException URI'net.tcp://192.168.1.45:4329/ServerTasks'已存在注册.
我想要做的是绑定到机器上的所有网络地址,以便客户端应用程序可以从他们看到的任何网络到达服务.当我运行此代码时,它会找到并尝试为大约5个不同的IP设置绑定,包括127.0.0.1.
192.168.1.45是它尝试绑定的第二个IP.在它抛出异常的时候,我可以看到(使用netstat)程序已经绑定到端口4329上列表中的第一个IP.在异常中提到的地址上没有绑定到端口4329的任何东西.
对不起,这里没有太多细节,我想简要介绍一下.如果有人需要更多信息我会乐意提供它.
注意:我已经尝试将PortSharingEnabled设置为true,以便在foreach循环中创建NetTcpBinding,但我仍然遇到相同的错误.
任何帮助或建议将非常适合!
谢谢
Mel*_*een 10
感谢Corazza的信息!
我已经想出如何实现这一目标.我正在以错误的方式解决这个问题.
我的最终目标是让服务监听机器上可用的每个IP地址.尝试单独绑定到每个地址是这样做的错误方法.
相反,我只需要将服务绑定到计算机的主机名(而不是'localhost'),WCF会自动侦听所有适配器.
这是更正后的代码:
public static void StartHosts()
{
try
{
// Formulate the uri for this host
string uri = string.Format(
"net.tcp://{0}:{1}/ServerTasks",
Dns.GetHostName(),
ServerSettings.Instance.TCPListeningPort
);
// Create a new host
ServiceHost host = new ServiceHost(typeof(ServerTasks), new Uri(uri));
// Add the endpoint binding
host.AddServiceEndpoint(
typeof(ServerTasks),
new NetTcpBinding(SecurityMode.Transport)
{
TransferMode = TransferMode.Streamed
},
uri
);
// Add the meta data publishing
var smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (smb == null)
smb = new ServiceMetadataBehavior();
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
host.Description.Behaviors.Add(smb);
host.AddServiceEndpoint(
ServiceMetadataBehavior.MexContractName,
MetadataExchangeBindings.CreateMexTcpBinding(),
"net.tcp://localhost/ServerTasks/mex"
);
// Run the host
host.Open();
}
catch (Exception exc)
{
DebugLogger.WriteException(exc);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18027 次 |
| 最近记录: |