Cliente Android com Código Kotlin

Veja como é feito o cliente Android deste projeto de chat em tempo real, incluindo os principais trechos de código em Kotlin.

📱 Código Kotlin: MainActivity

Estabelecendo a conexão e criando as threads:


private lateinit var socket: Socket
private lateinit var writer: PrintWriter
private lateinit var reader: BufferedReader

fun connectToServer(ip: String, port: Int) {
    thread {
        try {
            socket = Socket(ip, port)
            writer = PrintWriter(socket.getOutputStream(), true)
            reader = BufferedReader(InputStreamReader(socket.getInputStream()))

            runOnUiThread {
                Toast.makeText(this, "Conectado ao servidor!", Toast.LENGTH_SHORT).show()
            }

            receiveMessages()

        } catch (e: Exception) {
            runOnUiThread {
                Toast.makeText(this, "Erro: ${e.message}", Toast.LENGTH_LONG).show()
            }
        }
    }
}
    

Thread para receber mensagens:


fun receiveMessages() {
    thread {
        try {
            var line: String?
            while (reader.readLine().also { line = it } != null) {
                runOnUiThread {
                    txtMessages.append("Servidor: $line\n")
                }
            }
        } catch (e: Exception) {
            Log.e("Chat", "Erro ao receber mensagens", e)
        }
    }
}
    

Enviando mensagem do botão:


btnSend.setOnClickListener {
    val message = edtMessage.text.toString()
    thread {
        writer.println(message)
    }
    edtMessage.text.clear()
}
    

📄 Layout XML: activity_main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <TextView
        android:id="@+id/txtMessages"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="Mensagens aqui..."
        android:background="#EFEFEF"
        android:padding="8dp" />

    <EditText
        android:id="@+id/edtMessage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Digite sua mensagem..." />

    <Button
        android:id="@+id/btnSend"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Enviar" />

</LinearLayout>
    

📂 Repositório GitHub

Código completo com cliente + servidor:

Ver no GitHub