我无法在网络上找到答案。

有人知道如何在Netty服务器中获取动态分配的端口信息吗?

通过以下方式引导服务器:

override fun startSocket() {
    try {
        val serverBootstrap = ServerBootstrap()
        serverBootstrap.group(group)
        serverBootstrap.channel(NioServerSocketChannel::class.java)
        if(peerInfo is DynamicPortPeerInfo) {
            serverBootstrap.localAddress(InetSocketAddress(peerInfo.host, 0))
        } else {
            serverBootstrap.localAddress(InetSocketAddress(peerInfo.host, peerInfo.port))
        }
        serverBootstrap.childHandler(object : ChannelInitializer<SocketChannel>() {
            override fun initChannel(socketChannel: SocketChannel) {
                socketChannel.pipeline()
                        .addLast(NettyIO.framePrepender)
                        .addLast(LengthFieldBasedFrameDecoder(MAX_PAYLOAD_SIZE, 0, packetSizeLength, 0, packetSizeLength))
                        .addLast(ServerHandler())
            }
        })
        val channelFuture = serverBootstrap.bind().sync()
        channelFuture.channel().closeFuture().sync()
    } catch (e: Exception) {
        logger.error(e.toString())
    }
}

最佳答案

您可以通过访问ChannelFuture返回的bind()获得此信息。

就像是:

ChannelFuture channelFuture = serverBootstrap.bind().sync()
InetSocketAddress localAddress = (InetSocketAddress) channelFuture.channel().localAddress();
int port = localAddress.getPort();

07-24 22:12