Created
August 31, 2019 19:54
-
-
Save Silverbaq/1fdaf8aee72b86b8c9e2bd47fd1976f4 to your computer and use it in GitHub Desktop.
A simple socket client in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.....