add websockets work
This commit is contained in:
@@ -45,6 +45,7 @@ kotlin {
|
||||
}
|
||||
|
||||
api "io.ktor:ktor-client-core:$ktor_version"
|
||||
api "io.ktor:ktor-client-websockets:$ktor_version"
|
||||
}
|
||||
}
|
||||
commonTest {
|
||||
@@ -58,6 +59,8 @@ kotlin {
|
||||
implementation kotlin('stdlib-jdk8')
|
||||
|
||||
api "io.ktor:ktor-client:$ktor_version"
|
||||
api "io.ktor:ktor-client-websockets-jvm:$ktor_version"
|
||||
api "io.ktor:ktor-client-okhttp:$ktor_version"
|
||||
}
|
||||
}
|
||||
jvmTest {
|
||||
@@ -70,6 +73,7 @@ kotlin {
|
||||
implementation kotlin('stdlib-js')
|
||||
|
||||
api "io.ktor:ktor-client-js:$ktor_version"
|
||||
api "io.ktor:ktor-client-websockets-js:$ktor_version"
|
||||
}
|
||||
}
|
||||
jsTest {
|
||||
|
@@ -0,0 +1,45 @@
|
||||
package com.insanusmokrassar.postssystem.ktor.client
|
||||
|
||||
import com.insanusmokrassar.postssystem.ktor.*
|
||||
import com.insanusmokrassar.postssystem.utils.common.safely
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.features.websocket.ws
|
||||
import io.ktor.client.request.url
|
||||
import io.ktor.http.HttpMethod
|
||||
import io.ktor.http.cio.websocket.*
|
||||
import kotlinx.coroutines.flow.*
|
||||
import kotlinx.coroutines.isActive
|
||||
|
||||
inline fun <reified T> createStandardWebsocketFlow(
|
||||
client: HttpClient,
|
||||
url: String,
|
||||
crossinline conversation: suspend (ByteArray) -> T
|
||||
): Flow<T> {
|
||||
val correctedUrl = url.asCorrectWebSocketUrl
|
||||
|
||||
return channelFlow {
|
||||
val producerScope = this
|
||||
safely(
|
||||
{
|
||||
producerScope.close()
|
||||
throw it
|
||||
}
|
||||
) {
|
||||
client.ws(
|
||||
correctedUrl
|
||||
) {
|
||||
while (true) {
|
||||
when (val received = incoming.receive()) {
|
||||
is Frame.Binary -> producerScope.send(
|
||||
conversation(received.readBytes())
|
||||
)
|
||||
else -> {
|
||||
producerScope.close()
|
||||
return@ws
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user