如果我使用端口 0 创建 TcpChannel,即允许.Net Remoting分配可用端口,是否有办法确定已分配哪个端口号?

我知道我可以在创建通道时指定端口号,但我不想这样做,因为我想在同一 Citrix 服务器上运行侦听应用程序的多个实例 - 每个实例侦听不同的端口。

理想情况下,我不想麻烦地保留一堆端口,然后跟踪哪些端口已被分配。我只想让端口自动分配 - 但随后我需要能够知道已分配哪个端口号。

有帮助吗?

解决方案 2

我的解决方案如下:

  • 使用以下代码来识别客户端应用程序的每个实例的未使用端口:

    IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
    
    using (Socket socket = new Socket(
                 AddressFamily.InterNetwork, 
                 SocketType.Stream, 
                 ProtocolType.Tcp))
    {
        socket.Bind(endPoint);
        IPEndPoint local = (IPEndPoint)socket.LocalEndPoint;
        return local.Port;
    }
    
  • 将未使用的端口号存储在客户端应用程序中。

  • 通过命令行参数将存储的端口号传递给主机应用程序,以便在设置 TcpChannel 和调用 Activator.GetObject 时使用。

  • 在传递给 Activator.GetObject 的 URL 中使用客户端应用程序中存储的端口号。

其他提示

我对此并不了解,但是在MSDN上浏览它说明零后使用会返回 TcpServerChannel ,而 TcpServerChannel 会有 GetChannelUri( )方法;那包括端口号吗? (您可能需要通过 new Uri(s).Port 进行解析。

再次,完整的猜测工作。如果没有,请说出:-p

由AakashM编辑添加这是正确的方法。以下

var channel = new TcpChannel(0);

可以使用

检索包含的服务器通道的动态分配的帖子
var channelData = (ChannelDataStore)channel.ChannelData;
var port = new System.Uri(channelData.ChannelUris[0]).Port;

丑陋的演员是必要的,因为 TcpChannel.ChannelData 属性被输入为 object ...

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top