Android Kotlin Web Server

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
val hash : ConcurrentHashMap<String, String> = ConcurrentHashMap()
val server = ServerSocket(8888)
btnStart?.setOnClickListener {
hash
["is_started"]="true"
thread {
while
(hash["is_started"].toBoolean()) {
val client = server.accept()
thread { ClientHandler(client).run() }
}
}
}
btnStop?.setOnClickListener {
hash
["is_started"]="false"
}
class ClientHandler(client: Socket) {
private val client: Socket = client
var isr = InputStreamReader(client.getInputStream())
var reader = StringBuilder()
private val writer: OutputStream = client.getOutputStream()

fun run() {
try {
var br = BufferedReader(isr)
while (br.ready()) {
reader.append(br.read().toChar())
}
val body = "OOFnivek\n"
val
response = String.format(
"HTTP/1.1 200 OK\nContent-Length: %d\r\n\r\n%s",
body.length,
body
)
writer.write(response.toByteArray())
} catch (ex: Exception) {
client.close()
}
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kevin FOO

Kevin FOO

A software engineer, a rock climbing, inline skating enthusiast, a husband, a father.