Created
April 17, 2023 13:28
-
-
Save bgrebennikov/aad21a83b326eca1be17f8eb892544f8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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