Skip to content

Instantly share code, notes, and snippets.

@latant
Created March 9, 2020 22:59
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save latant/dc41c1e31f337a0116404efb4d1a1315 to your computer and use it in GitHub Desktop.
Save latant/dc41c1e31f337a0116404efb4d1a1315 to your computer and use it in GitHub Desktop.
An example using Java RMI with Kotlin
import java.io.Serializable
import java.rmi.Remote
import java.rmi.RemoteException
import java.rmi.registry.LocateRegistry
import java.rmi.server.UnicastRemoteObject
class Person(val name: String, val age: Int): Serializable
interface HelloService : Remote {
@Throws(RemoteException::class)
fun hello(person: Person): String
}
class HelloServiceImpl : HelloService {
override fun hello(person: Person) = "Hello, ${person.name}, you are ${person.age} years old.".also(::println)
}
inline fun <reified T: Remote> publish(port: Int, obj: T) {
LocateRegistry.createRegistry(port).bind(T::class.simpleName, UnicastRemoteObject.exportObject(obj, 0))
}
inline fun <reified T: Remote> consume(host: String, port: Int): T {
return LocateRegistry.getRegistry(host, port).lookup(T::class.simpleName) as T
}
object Server {
@JvmStatic
fun main(args: Array<String>) {
publish<HelloService>(4000, HelloServiceImpl())
println("Server started")
}
}
object Client {
@JvmStatic
fun main(args: Array<String>) {
val helloService = consume<HelloService>("localhost", 4000)
println(helloService.hello(Person("Bob", 20)))
}
}
@MohammadAttarzoghi
Copy link

Thanks dear friend.
I am familiar with java but new to kotlin
This code taught me a lot.
Very usefull
Again thanks for your time and sharing such a clean code

@MohammadAttarzoghi
Copy link

can you please intodunce good sources to learn more in kotlin?
In kotlinlang.org I could not find good lessons for topics such as RMI

@134130
Copy link

134130 commented Aug 9, 2023

Love it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment