|
| 1 | +/* |
| 2 | + * Copyright 2015-2020 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package io.rsocket.kotlin.test.server |
| 18 | + |
| 19 | +import io.ktor.application.* |
| 20 | +import io.ktor.routing.* |
| 21 | +import io.ktor.server.cio.* |
| 22 | +import io.ktor.server.engine.* |
| 23 | +import io.ktor.websocket.* |
| 24 | +import io.rsocket.kotlin.core.* |
| 25 | +import io.rsocket.kotlin.test.* |
| 26 | +import io.rsocket.kotlin.transport.ktor.* |
| 27 | +import io.rsocket.kotlin.transport.ktor.server.* |
| 28 | +import kotlinx.coroutines.* |
| 29 | +import java.io.* |
| 30 | + |
| 31 | +fun main() { |
| 32 | + start().await() |
| 33 | +} |
| 34 | + |
| 35 | +fun start(): TestServer { |
| 36 | + val server = TestServer() |
| 37 | + server.start() |
| 38 | + return server |
| 39 | +} |
| 40 | + |
| 41 | +class TestServer : Closeable { |
| 42 | + private val job = Job() |
| 43 | + private var wsServer: ApplicationEngine? = null |
| 44 | + private val rSocketServer = RSocketServer { |
| 45 | +// loggerFactory = PrintLogger.withLevel(LoggingLevel.DEBUG) |
| 46 | + } |
| 47 | + |
| 48 | + fun start(): Unit = runCatching { |
| 49 | + val scope = CoroutineScope(job) |
| 50 | + |
| 51 | + //start TCP server |
| 52 | + rSocketServer.bindIn(scope, TcpServerTransport(port = 8000)) { TestRSocket() } |
| 53 | + |
| 54 | + //start WS server |
| 55 | + wsServer = scope.embeddedServer(CIO, port = 9000) { |
| 56 | + install(WebSockets) |
| 57 | + install(RSocketSupport) { server = rSocketServer } |
| 58 | + |
| 59 | + routing { |
| 60 | + rSocket { TestRSocket() } |
| 61 | + } |
| 62 | + }.start() |
| 63 | + |
| 64 | + Thread.sleep(1000) //await start |
| 65 | + }.onFailure { close() }.getOrThrow() |
| 66 | + |
| 67 | + fun await() { |
| 68 | + runBlocking { job.join() } |
| 69 | + } |
| 70 | + |
| 71 | + override fun close() { |
| 72 | + runBlocking { job.cancelAndJoin() } |
| 73 | + wsServer?.stop(0, 1000) |
| 74 | + } |
| 75 | +} |
0 commit comments