Newer
Older
Twilight / src / main / kotlin / net / taehui / twilight / qwilight / QwilightBoot.kt
@Taehui Taehui on 27 Jun 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.ServerSocketChannel
import io.netty.channel.socket.SocketChannel
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 io.netty.handler.ssl.SslHandler
import net.taehui.twilight.Logger
import javax.net.ssl.SSLContext

class QwilightBoot(
    eventLoopGroup: EventLoopGroup, eventChannel: Class<out ServerSocketChannel>, sslContext: SSLContext
) : Logger, AutoCloseable {
    private val mainBootstrap: ServerBootstrap = ServerBootstrap().group(eventLoopGroup).channel(eventChannel)
        .childHandler(object : ChannelInitializer<SocketChannel>() {
            public override fun initChannel(ch: SocketChannel) {
                ch.pipeline().addLast(SslHandler(sslContext.createSSLEngine().apply {
                        useClientMode = false
                    })).addLast(ProtobufVarint32FrameDecoder())
                    .addLast(ProtobufDecoder(EventOuterClass.Event.getDefaultInstance()))
                    .addLast(ProtobufVarint32LengthFieldPrepender()).addLast(ProtobufEncoder())
                    .addLast(QwilightAvatar())
            }
        })
    private val mainChannel: Channel

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

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