Advertisement
Guest User

Untitled

a guest
Sep 11th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. import java.io.OutputStream
  2. import java.net.Socket
  3. import java.nio.charset.Charset
  4. import java.util.*
  5. import kotlin.concurrent.thread
  6.  
  7. fun main(args: Array<String>) {
  8. val address = "localhost"
  9. val port = 9999
  10.  
  11. val client = Client(address, port)
  12. client.run()
  13. }
  14.  
  15. class Client(address: String, port: Int) {
  16. private val connection: Socket = Socket(address, port)
  17. private var connected: Boolean = true
  18.  
  19. init {
  20. println("Connected to server at $address on port $port")
  21. }
  22.  
  23. private val reader: Scanner = Scanner(connection.getInputStream())
  24. private val writer: OutputStream = connection.getOutputStream()
  25.  
  26. fun run() {
  27. thread { read() }
  28. while (connected) {
  29. val input = readLine() ?: ""
  30. if ("exit" in input) {
  31. connected = false
  32. reader.close()
  33. connection.close()
  34. } else {
  35. write(input)
  36. }
  37. }
  38.  
  39. }
  40.  
  41. private fun write(message: String) {
  42. writer.write((message + '\n').toByteArray(Charset.defaultCharset()))
  43. }
  44.  
  45. private fun read() {
  46. while (connected)
  47. println(reader.nextLine())
  48. }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement