All Downloads are FREE. Search and download functionalities are using the official Maven repository.

dev.pellet.server.PelletServerClient.kt Maven / Gradle / Ivy

There is a newer version: 0.0.16
Show newest version
package dev.pellet.server

import dev.pellet.logging.debug
import dev.pellet.logging.pelletLogger
import dev.pellet.server.buffer.PelletBuffer
import dev.pellet.server.buffer.PelletBufferPooling
import dev.pellet.server.extension.awaitWrite
import java.net.InetSocketAddress
import java.net.UnixDomainSocketAddress
import java.nio.channels.AsynchronousSocketChannel

sealed class CloseReason {

    object ClientInitiated : CloseReason()
    object ServerInitiated : CloseReason()
    data class ServerException(val throwable: Throwable) : CloseReason()
}

class PelletServerClient(
    private val socket: AsynchronousSocketChannel,
    private val pool: PelletBufferPooling
) {

    private val logger = pelletLogger()

    val remoteHostString: String
        get() {
            return when (val remoteAddress = socket.remoteAddress) {
                is InetSocketAddress -> remoteAddress.hostString
                is UnixDomainSocketAddress -> remoteAddress.path.toString()
                else -> remoteAddress.toString()
            }
        }

    suspend fun writeAndRelease(buffer: PelletBuffer): Result {
        val result = runCatching {
            socket.awaitWrite(buffer.byteBuffer)
        }
        pool.release(buffer)
        return result
    }

    fun close(source: CloseReason): Result {
        logger.debug { "closed $socket (initiator: $source)" }
        return runCatching {
            socket.close()
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy