Skip to content

Instantly share code, notes, and snippets.

@Silverbaq
Created August 31, 2019 19:54
Show Gist options
  • Save Silverbaq/1fdaf8aee72b86b8c9e2bd47fd1976f4 to your computer and use it in GitHub Desktop.
Save Silverbaq/1fdaf8aee72b86b8c9e2bd47fd1976f4 to your computer and use it in GitHub Desktop.
A simple socket client in Kotlin
import java.io.OutputStream
import java.net.Socket
import java.nio.charset.Charset
import java.util.*
import kotlin.concurrent.thread
fun main(args: Array<String>) {
val address = "localhost"
val port = 9999
val client = Client(address, port)
client.run()
}
class Client(address: String, port: Int) {
private val connection: Socket = Socket(address, port)
private var connected: Boolean = true
init {
println("Connected to server at $address on port $port")
}
private val reader: Scanner = Scanner(connection.getInputStream())
private val writer: OutputStream = connection.getOutputStream()
fun run() {
thread { read() }
while (connected) {
val input = readLine() ?: ""
if ("exit" in input) {
connected = false
reader.close()
connection.close()
} else {
write(input)
}
}
}
private fun write(message: String) {
writer.write((message + '\n').toByteArray(Charset.defaultCharset()))
}
private fun read() {
while (connected)
println(reader.nextLine())
}
}
@MutatedGamer
Copy link

reader.close() deadlocks the client here, because reader.nextLine() takes a lock that is checked. connection.close() never gets called. Any way around this?

@eavcodes
Copy link

You should send a end of line command (see ASCII table), because the function is nextLine(). So, it means that the process still waiting for EOL byte in order to release the process and go to next step.....

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