Skip to content

Instantly share code, notes, and snippets.

@BaerMitUmlaut
Created December 6, 2018 12:33
Show Gist options
  • Save BaerMitUmlaut/30c05f4b13d14260693cd2204ffbb861 to your computer and use it in GitHub Desktop.
Save BaerMitUmlaut/30c05f4b13d14260693cd2204ffbb861 to your computer and use it in GitHub Desktop.
Simple client server communication with object streams in Kotlin.
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.Serializable
import java.net.ServerSocket
import java.net.Socket
import java.util.*
data class Question(val question: String, val answers: List<String>): Serializable
fun main(args: Array<String>) {
when {
args.size < 1 -> println("Start with -s for server and -c for client.")
args[0].toLowerCase() == "-s" -> server()
args[0].toLowerCase() == "-c" -> client()
}
}
fun server() {
val serverSock = ServerSocket(34567)
while (true) {
val sock = serverSock.accept()
val outStream = ObjectOutputStream(sock.getOutputStream())
val inStream = ObjectInputStream(sock.getInputStream())
val question = Question("What day is it?", listOf(
"February",
"Orange",
"A great day!"
))
outStream.writeObject(question)
val answer = inStream.readObject()
if (answer is String) {
println("Client answered with $answer")
}
inStream.close()
outStream.close()
sock.close()
}
}
fun client() {
val sock = Socket("127.0.0.1", 34567)
val outStream = ObjectOutputStream(sock.getOutputStream())
val inStream = ObjectInputStream(sock.getInputStream())
val question = inStream.readObject()
if (question is Question) {
println("Server asked: $question.question")
outStream.writeObject(question.answers[Random().nextInt(3)])
}
outStream.close()
inStream.close()
sock.close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment