Newer
Older
Twilight / src / main / kotlin / net / taehui / twilight / qwilight / QwilightBoot.kt
@taehui taehui on 19 Aug 1 KB v1.0-SNAPSHOT
package net.taehui.twilight.qwilight

import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.Channel
import io.netty.channel.ChannelInitializer
import io.netty.channel.EventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder
import io.netty.handler.codec.protobuf.ProtobufDecoder
import io.netty.handler.codec.protobuf.ProtobufEncoder
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender
import net.taehui.twilight.Logger

class QwilightBoot(eventLoopGroup: EventLoopGroup) : Logger, AutoCloseable {
    private val mainBootstrap: ServerBootstrap =
        ServerBootstrap().group(eventLoopGroup).channel(NioServerSocketChannel::class.java)
            .childHandler(object : ChannelInitializer<SocketChannel>() {
                public override fun initChannel(ch: SocketChannel) {
                    ch.pipeline()
                        .addLast(HAProxyMessageDecoder())
                        .addLast(ProtobufVarint32FrameDecoder())
                        .addLast(ProtobufDecoder(EventOuterClass.Event.getDefaultInstance()))
                        .addLast(ProtobufVarint32LengthFieldPrepender())
                        .addLast(ProtobufEncoder())
                        .addLast(QwilightAvatar())
                }
            })
    private val mainChannel: Channel

    init {
        logInfo("Loading Qwilight")
        mainChannel = mainBootstrap.bind(4000).channel().closeFuture().addListener {
            logInfo("Closed Qwilight")
        }.channel()
    }

    override fun close() {
        mainChannel.close()
    }
}