Sample code below is a very simple web server written in Kotlin. A [Start] button to start listening, a [Stop] button to stop listening and text view to display WiFi address.
Remember to add these 2 permissions else the app will crash upon start.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Codes for the 2 class variable and in my example I had the port hard coded to 8888.
val hash : ConcurrentHashMap<String, String> = ConcurrentHashMap()
val server = ServerSocket(8888)
Codes for getting WiFi address can be found at “Android Kotlin Get WiFi IP” post. And the codes for the button listener below.
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"
}
After that you will also be needing a client handler class. Codes below the screenshot. Content length HTTP header is very important else it will not know when to stop.
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()
}
}
}
Successful test with the apps listed below.
1. curl in Mac terminal
2. Chrome in Mac