hey peeps, I'm working on a noddy project for my o...
# ktor
c
hey peeps, I'm working on a noddy project for my own learning and I need to create a websocket connection (as a client) to a home assistant instance. I need bi-directional, asynchronous communication and I've got it working, but I think I'm being an idiot 🧵
Copy code
class CommonHaService {
    val json = Json {}
    private val client = HttpClient {
        install(WebSockets)
    }

    var commandId = 1

    private val commandChannel = Channel<HAServiceCall>()
    private val commandFlow: Flow<HAServiceCall> = flow {
        while (true) {
            // Forward received commands to command flow collector
            emit(commandChannel.receive())
        }
    }

    val eventFlow = flow<HaServiceEvent> {
        var authed = false

        client.webSocket("...") {
            async {
                commandFlow.collect {
                    // Handle sending data
                }
            }

            incoming.receiveAsFlow().catch {
                emit(HaServiceEvent.Disconnected)
            }.collect {
                // Handle receiving data
            }
        }
    }
}
a
Hi @czuckie,It's easier than you think you can check my projects hope they will help you Server side : https://github.com/adelayman1/SocketNoteApiKtor/ Client side :https://github.com/adelayman1/ComposeNotesAppKtor-Client
👍🏾 1
c
cheers Adel, I'll have a look, thanks for the links!
❤️ 2
I've had a quick look, are you using websockets?
I can't seem to find any references 😞
a
Yeah
this is exactly what I needed, thanks Adel! 🤜 💥 🤛
a
You are welcome 🖤