Skip to content

Instantly share code, notes, and snippets.

@banasiak
Created November 23, 2017 17:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save banasiak/7069bb7da0cd2dd322c2d554677ac37a to your computer and use it in GitHub Desktop.
Save banasiak/7069bb7da0cd2dd322c2d554677ac37a to your computer and use it in GitHub Desktop.
An example echo server written in Kotlin.
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.ServerSocket
import kotlin.concurrent.thread
const val SERVER_PORT = 1337
fun main(args: Array<String>) {
println("Hello World!")
val socketListener = ServerSocket(SERVER_PORT)
var clientNumber = 0
socketListener.use {
while (true) {
val socket = socketListener.accept()
thread(start = true) {
clientNumber++
val thisClient = clientNumber
val output = PrintWriter(socket.getOutputStream(), true)
val input = BufferedReader(InputStreamReader(socket.getInputStream()))
output.println("Welcome to the Kotlin echo server. You are client #$thisClient.")
output.println("End this conversation by sending a single '.' on a new line.")
while (true) {
val line = input.readLine()
if (line == ".") {
println("Client #$thisClient closed connection.")
output.println("Kthxbai!")
socket.close()
return@thread
}
println("Client #$thisClient said: $line")
output.println("I heard you say: " + line)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment