Skip to content

Instantly share code, notes, and snippets.

@bgrebennikov
Created April 17, 2023 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bgrebennikov/aad21a83b326eca1be17f8eb892544f8 to your computer and use it in GitHub Desktop.
Save bgrebennikov/aad21a83b326eca1be17f8eb892544f8 to your computer and use it in GitHub Desktop.
package com.bgrebennikovv.github.wsexample.repositories
import com.bgrebennikovv.github.wsexample.network.NetworkClient
import io.ktor.client.plugins.websocket.*
import io.ktor.http.*
import io.ktor.websocket.*
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
class ChatRepositoryImpl : ChatRepository, KoinComponent {
private val networkClient: NetworkClient by inject()
private val client = networkClient.getInstance()
private val session = runBlocking {
client.webSocketSession(method = HttpMethod.Get,
host = "192.168.43.210",
port = 8080,
path = "/chat")
}
override suspend fun sendMessage(message: String) {
try{
session.outgoing.send(Frame.Text(message))
} catch (e: Exception){
e.printStackTrace()
}
}
override suspend fun receiveMessage(message: (String) -> Unit) {
try{
client.webSocket(
method = HttpMethod.Get,
host = "192.168.43.210",
port = 8080,
path = "/chat"
){
session.incoming.consumeEach {
when(it){
is Frame.Text -> {
message.invoke(it.readText())
}
else -> {}
}
}
}
} catch (e: Exception){
e.printStackTrace()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment