controls-kt/demo/magix-demo/src/main/kotlin/zmq.kt

70 lines
2.3 KiB
Kotlin
Raw Normal View History

import kotlinx.coroutines.cancel
2021-07-03 14:16:31 +03:00
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.isActive
import kotlinx.serialization.json.*
2021-07-03 14:16:31 +03:00
import org.slf4j.LoggerFactory
2022-08-02 09:46:31 +03:00
import space.kscience.magix.api.MagixEndpoint
import space.kscience.magix.api.MagixMessage
import space.kscience.magix.server.startMagixServer
import space.kscince.magix.zmq.ZmqMagixEndpoint
import java.awt.Desktop
import java.net.URI
2021-07-03 14:16:31 +03:00
2022-06-04 15:46:13 +03:00
suspend fun MagixEndpoint.sendJson(
2021-07-03 14:16:31 +03:00
origin: String,
format: String = "json",
target: String? = null,
id: String? = null,
parentId: String? = null,
user: JsonElement? = null,
builder: JsonObjectBuilder.() -> Unit
2022-06-05 12:26:34 +03:00
): Unit = broadcast(MagixMessage(format, buildJsonObject(builder), origin, target, id, parentId, user))
2021-07-03 14:16:31 +03:00
internal const val numberOfMessages = 100
2021-07-03 14:16:31 +03:00
suspend fun main(): Unit = coroutineScope {
val logger = LoggerFactory.getLogger("magix-demo")
logger.info("Starting magix server")
val server = startMagixServer(
buffer = 10,
enableRawRSocket = false //Disable rsocket to avoid kotlin 1.5 compatibility issue
)
server.apply {
val host = "localhost"//environment.connectors.first().host
val port = environment.connectors.first().port
val uri = URI("http", null, host, port, "/state", null, null)
Desktop.getDesktop().browse(uri)
}
2021-07-03 14:16:31 +03:00
logger.info("Starting client")
//Create zmq magix endpoint and wait for to finish
ZmqMagixEndpoint("localhost","tcp").use { client ->
2021-07-03 14:16:31 +03:00
logger.info("Starting subscription")
client.subscribe().onEach {
println(it.payload)
2022-06-04 15:46:13 +03:00
if (it.payload.jsonObject["index"]?.jsonPrimitive?.int == numberOfMessages) {
logger.info("Index $numberOfMessages reached. Terminating")
cancel()
}
}.catch { it.printStackTrace() }.launchIn(this)
2021-07-03 14:16:31 +03:00
var counter = 0
while (isActive) {
delay(500)
val index = (counter++).toString()
logger.info("Sending message number $index")
client.sendJson("magix-demo", id = index) {
2021-07-03 14:16:31 +03:00
put("message", "Hello world!")
put("index", index)
2021-07-03 14:16:31 +03:00
}
}
}
}