NettyWsSession.kt

  1. package com.hexagontk.http.server.netty

  2. import com.hexagontk.http.handlers.HttpContext
  3. import com.hexagontk.http.model.HttpRequestPort
  4. import com.hexagontk.http.model.ws.WsSession
  5. import io.netty.buffer.Unpooled
  6. import io.netty.channel.ChannelHandlerContext
  7. import io.netty.handler.codec.http.websocketx.*
  8. import java.net.URI

  9. internal class NettyWsSession(
  10.     nettyContext: ChannelHandlerContext,
  11.     context: HttpContext,
  12. ) : WsSession {

  13.     override val attributes: Map<*, *> by lazy { context.attributes }
  14.     override val request: HttpRequestPort by lazy { context.request }
  15.     override val exception: Exception? by lazy { context.exception }
  16.     override val pathParameters: Map<String, String> by lazy { context.pathParameters }

  17.     override val uri: URI get() = throw UnsupportedOperationException()

  18.     private val channel = nettyContext.channel()

  19.     override fun send(data: ByteArray) {
  20.         val webSocketFrame = BinaryWebSocketFrame(Unpooled.wrappedBuffer(data))
  21.         channel.writeAndFlush(webSocketFrame)
  22.     }

  23.     override fun send(text: String) {
  24.         val webSocketFrame = TextWebSocketFrame(text)
  25.         channel.writeAndFlush(webSocketFrame)
  26.     }

  27.     override fun ping(data: ByteArray) {
  28.         channel.writeAndFlush(PingWebSocketFrame(Unpooled.wrappedBuffer(data)))
  29.     }

  30.     override fun pong(data: ByteArray) {
  31.         channel.writeAndFlush(PongWebSocketFrame(Unpooled.wrappedBuffer(data)))
  32.     }

  33.     override fun close(status: Int, reason: String) {
  34.         val webSocketFrame = CloseWebSocketFrame(status, reason)
  35.         channel.writeAndFlush(webSocketFrame)
  36.     }
  37. }