如何让我的WCF服务运行在本地端口?我的、端口、WCF

2023-09-04 03:11:51 作者:我心微凉、终已成伤

我使用的是同一台机器上的多个自承载的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是here)

 
精彩推荐
图片推荐