What's the best way to send objects from a server via some interchange format (Json/Yaml/etc.) with websockets? Should I just serialize the object, then send the raw string/binary data via the associated Frame?
d
Damian Lall
09/11/2019, 4:16 PM
I just serialize my objects into JSON with Klaxon and send it in a text frame. I find polymorphic serialization very useful in these cases as the receiver is easily able to determine what the objects are through the use of a
type
attribute in the JSON.
Damian Lall
09/11/2019, 4:22 PM
This are the models I use for a simple messaging app (this code is shared between the app and server).
Copy code
@TypeFor("type", TransmissionAdapter::class)
sealed class Transmission(val type: String)
class TransmissionAdapter: TypeAdapter<Transmission> {
override fun classFor(type: Any): KClass<out Transmission> = when (type as String) {
"user_join" -> UserJoin::class
"user_leave" -> UserLeave::class
"message" -> Message::class
else -> throw IllegalArgumentException("Received unknown type $type")
}
}
data class UserJoin(
val name: String
) : Transmission("user_join")
data class UserLeave(
val name: String
) : Transmission("user_leave")
data class Message(
val channel: String,
val text: String
) : Transmission("message")