Home > Back-end >  How to get the value of another function synchronously
How to get the value of another function synchronously

Time:07-08

I am using the ktor websocket module When I send data to the client, how do I get the data back from the client after this send?

    val result = serverSession.send(json)
    // result

Just like this

It is actually the Unit type But I want to get the String

CodePudding user response:

There are great examples on official site of Ktor.

If you are server-side, check this link (https://ktor.io/docs/websocket.html#handle-single-session) and the below example.

webSocket("/echo") {
            send("Please enter your name")
            for (frame in incoming) {
                when (frame) {
                    is Frame.Text -> {
                        val receivedText = frame.readText()
                        if (receivedText.equals("bye", ignoreCase = true)) {
                            close(CloseReason(CloseReason.Codes.NORMAL, "Client said BYE"))
                        } else {
                            send(Frame.Text("Hi, $receivedText!"))
                        }
                    }
                }
            }
        }

If you are client-side, check this link (https://ktor.io/docs/websocket-client.html#example) and the below example.

client.webSocket(method = HttpMethod.Get, host = "127.0.0.1", port = 8080, path = "/echo") {
            while(true) {
                val othersMessage = incoming.receive() as? Frame.Text
                println(othersMessage?.readText())
                val myMessage = Scanner(System.`in`).next()
                if(myMessage != null) {
                    send(myMessage)
                }
            }
        }
  • Related