有没有办法在netty中获取端口信息?
Is there any way to get port info in netty?
我在网络上找不到答案。
有谁知道如何在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())
}
}
您可以通过访问 bind()
返回的 ChannelFuture
来获取它。
类似于:
ChannelFuture channelFuture = serverBootstrap.bind().sync()
InetSocketAddress localAddress = (InetSocketAddress) channelFuture.channel().localAddress();
int port = localAddress.getPort();
我在网络上找不到答案。
有谁知道如何在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())
}
}
您可以通过访问 bind()
返回的 ChannelFuture
来获取它。
类似于:
ChannelFuture channelFuture = serverBootstrap.bind().sync()
InetSocketAddress localAddress = (InetSocketAddress) channelFuture.channel().localAddress();
int port = localAddress.getPort();