I'm using <ktor.io> library. I want to know how to...
# getting-started
a
I'm using ktor.io library. I want to know how to setup ping sending in websocket from client side to the server every interval defined in the server side. I tried to find docs but there weren't any examples of ping-pong. Somebody can help?
s
#ktor ask in there
a
ok sir
c
the Chat App sample is pretty good at setting up the core functionality needed for websockets (https://ktor.io/samples/app/chat.html). I’ve recently been making a more complete/safe application based on that sample, which might help you as well. Most notably, I’ve turned the message handling on the server into
Actors
and made the app state immutable, to avoid multithreading issues. (https://github.com/cjbrooks12/witch-hunt) For sending regular pings from the server to the client, you could set up a ticker channel which notifies connected clients on each tick (https://kotlinlang.org/docs/reference/coroutines/channels.html#ticker-channels)
a
@Casey Brooks the chat example is straight forward its great but after setting the server side how could i start getting ping/pong throughout the lifecycle of websocket? I'm so confused, from client side i've just connected to server and start listening for pings and same from server side no responses at all from both sides they are just not finishing (i.e. alive) but no pings what so ever
c
You can have external mechanisms pushing messages to the client, such as the ticker channel. The ticker would be defined outside of the websocket, but on each tick passes a message to the ChatApp class, which in turn forwards the tick to the connected clients. Clients would then receive that tick and respond as needed, either by updating the UI, or they may send a message back to the server
The core idea of websockets is that it is not the request-response mechanism used for HTTP. You can pass as many messages as you need from either end of the socket, in any order, without needing a strict request-response cycle
a
so what is use of package io.ktor.http.cio.websocket.pinger and io.ktor.http.cio.websocket.ponger
c
Hmm, I was not aware of those APIs. Looking at the setup, it might be internally implemented already, there’s a
pingPeriod
option available when you install the websocket
Yeah, looking in the source, that
pinger
method is used in the
DefaultWebSocketSessionImpl
class, though I’m not quite sure what it’s doing or when it’s actually pinging
a
@Casey Brooks Its not working, that pinger ponger method. 😞