如何让我的WCF服务运行在本地端口? [英] How do I get the local port my WCF service runs on?

查看:101
本文介绍了如何让我的WCF服务运行在本地端口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是同一台机器上的多个自承载的WCF服务。我需要打开他们每个人不同的端口(明显),所以我用网络:TCP:// localhost:0程序。作为地址,因为我想它会分配一个自由港这样

I'm using multiple self-hosted WCF services on the same machine. I need to open each of them on a different port (obviously), so I used "net:tcp://localhost:0" as address since I figured it would assign a free port this way.

现在我需要知道哪些端口已实际分配。这code在服务器上运行,所以我需要的本地的端口。我该怎么办呢?

Now I need to know which port was assigned actually. This code runs on the server, so I need the local port. How do I do that?

推荐答案

找到东西的作品,即使它是一个有点脏。相反,会自动分配一个端口,一个自由港的明确要求,并用于创建服务:

Found something that works, even though it is a bit dirty. Instead of automatically assigning a port, a free port is explicitly requested and used to create the service:

Address = "net.tcp://localhost:" + FindFreeTcpPort ();

private static int FindFreeTcpPort ()
{
    TcpListener l = new TcpListener (IPAddress.Parse ("127.0.0.1"), 0);
    l.Start ();
    int port = ((IPEndPoint) l.LocalEndpoint).Port;
    l.Stop ();
    return port;
}

(该方法code是<一个href="http://stackoverflow.com/questions/138043/find-the-next-tcp-port-in-net/150974#150974">here)

这篇关于如何让我的WCF服务运行在本地端口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆