首页 > 解决方案 > 带有协程的 Kotlin 中的 Nio http 服务器

问题描述

我正在使用协程在 kotlin 中编写一个非常简单的 nio HTTP 服务器(将“Hello World!”传输到任何请求)。首先,我只使用一个线程来处理选择、读取和写入作业。一切顺利。 导致浏览器 然后我withTimeoutOrNull(timeout)用来限制服务器无休止地运行。我将超时限制设置为 10 秒,而我的选择器将选择阻塞 3 秒。

...
while (selector.select(3000) == 0) {
     println("HttServer is waiting")
     continue
}
...

但是当时间过时,什么也不会发生。 无休止 这是我的第一个问题:我的代码中发生了什么?withTimeoutOrNull(timeout)

忽略这个问题,我尝试使用主线程进行选择,并使用线程池作为调度程序进行读写。但是程序只是输出'HttpServer is waiting'而没有像我设置的那样等待3秒(几乎每微秒)。

HttpServer

class HttpServer(
        val port: Int,
        val dispatcher: CoroutineDispatcher,
) {
    val selector = Selector.open()

    val ssChannel: ServerSocketChannel = ServerSocketChannel.open()

    init {
        ssChannel.configureBlocking(false)
    }

    val htmlBuffer: ByteBuffer

    init {
        HttpServer::class.java.getResourceAsStream("/nio/index.html").use {
            htmlBuffer = ByteBuffer.allocate(it.available())
            htmlBuffer.clear()
            htmlBuffer.put(it.readBytes())
        }
    }

    suspend fun run(timeout: Long) {
        ssChannel.register(selector, SelectionKey.OP_ACCEPT)
        ssChannel.bind(InetSocketAddress(port))
        withTimeoutOrNull(timeout) {
            while (isActive) {
                while (selector.select(3000) == 0) {
                    println("HttpServer is waiting")
                    continue
                }
//                launch(dispatcher) {  // Something went wrong when uncomment this
                val keys = selector.selectedKeys()
                val iterator = keys.iterator()
                while (iterator.hasNext()) {
                    val key = iterator.next()
                    if (key.isAcceptable) {
                        val serverSocketChannel = key.channel() as ServerSocketChannel
                        val socketChannel = serverSocketChannel.accept()
                        socketChannel.configureBlocking(false)
                        socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024))
                        println("A client is connected")
                    } else if (key.isWritable) {
                        val socketChannel = key.channel() as SocketChannel
                        val httpBuffer = key.attachment() as ByteBuffer
                        httpBuffer.clear()

                        val stringBuilder = StringBuilder()
                        stringBuilder.append("HTTP/1.1 200 OK\n")
                        stringBuilder.append("Content-Type: text/html\n")
                        stringBuilder.append("\r\n")
                        stringBuilder.append(String(htmlBuffer.array()))

                        httpBuffer.put(stringBuilder.toString().toByteArray())
                        httpBuffer.flip()
                        socketChannel.write(httpBuffer)
                        httpBuffer.rewind()
                        println("Send message: ${String(httpBuffer.array())}")
                        key.cancel()
                        socketChannel.close()
                    } else if (key.isReadable) {
                        val socketChannel = key.channel() as SocketChannel
                        val httpBuffer = key.attachment() as ByteBuffer
                        httpBuffer.clear()
                        socketChannel.read(httpBuffer)
                        httpBuffer.flip()
                        println("Receive message: ${String(httpBuffer.array())}")
                        key.channel()
                        socketChannel.register(selector, SelectionKey.OP_WRITE, ByteBuffer.allocate(1024))
                    }
                    iterator.remove()
                }
//                }
            }
        }
    }

    fun shutdown() {
        selector.close()
        ssChannel.close()
    }
}

测试部分(kotest):

class HttpServerTest : FunSpec({
    test("HttpServer") {
        val tpcontext = newFixedThreadPoolContext(2, "worker")
        runBlocking {
            val server = HttpServer(2333, tpcontext)
            server.run(1000)
            server.shutdown()
        }
        tpcontext.close()
    }
})

标签: kotlinniokotlin-coroutines

解决方案


推荐阅读