https://kotlinlang.org logo
#ktor
Title
a

Andrii Iaremenko

02/07/2019, 10:26 AM
Hi all you guys! I'm Software Developer in Test. And I wanna to create a mock server for my needs. I choose from a lot of frameworks for Mock HttpServer -> Ktor. So. In this task I wanna to create WebSocket Server which will respond by specific URL (for example, localhost:8080/testPushEvents) by JSON object in real time. I mean that user subscribe on this url and will recieve all the time new JSON object. I try to create something like that, but it's not work.
Copy code
fun Application.main() {
    install(WebSockets){
          pingPeriod = Duration.ofSeconds(60)
          timeout = Duration.ofSeconds(15)
          maxFrameSize = Long.MAX_VALUE
          masking = false
    }
    install(Routing) {
        mockPushEvents()
    }
}
Copy code
fun Route.mockPushEvents(){

    route(""){
        webSocket("/") {

            while(true) {

                get("/testPushEvents"){
                    call.respond(someJsonData)
                }
                val frame = incoming.receive()
                when(frame){
                    is Frame.Text->{
                        val text = frame.readText()
                        outgoing.send(Frame.Text("Welcome $text"))
                        if (text.equals("bye" , ignoreCase = true)){
                            close(CloseReason(CloseReason.Codes.NORMAL, "Client said Bye"))
                        }
                    }
                }
            }
        }
    }
}
Thanks for a any help!