2025-05-27 19:14:58 +03:00

37 lines
1.4 KiB
Kotlin

package pw.binom.services
import kotlinx.coroutines.cancelAndJoin
import pw.binom.DEFAULT_BUFFER_SIZE
import pw.binom.io.ByteBufferFactory
import pw.binom.io.httpServer.HttpHandler
import pw.binom.io.httpServer.HttpServer2
import pw.binom.io.httpServer.ListenJob
import pw.binom.io.socket.InetSocketAddress
import pw.binom.network.NetworkManager
import pw.binom.pool.GenericObjectPool
import pw.binom.properties.ApplicationProperties
import pw.binom.strong.BeanLifeCycle
import pw.binom.strong.inject
import pw.binom.strong.properties.injectProperty
class HttpServer {
private val httpHandler: HttpHandler by inject()
private val networkManager: NetworkManager by inject()
private val applicationProperties: ApplicationProperties by injectProperty()
private val bufferPool by lazy { GenericObjectPool(ByteBufferFactory(DEFAULT_BUFFER_SIZE)) }
private var server: HttpServer2? = null
private var listenJob: ListenJob? = null
init {
BeanLifeCycle.postConstruct {
val server = HttpServer2(handler = httpHandler, dispatcher = networkManager, byteBufferPool = bufferPool)
this.server = server
listenJob = server.listen(InetSocketAddress.resolve("0.0.0.0", applicationProperties.port))
}
BeanLifeCycle.preDestroy {
listenJob?.cancelAndJoin()
server?.asyncCloseAnyway()
}
}
}