0

Hi there I'm writing a client app in android studio

this is my client class:


class Client : Socket()
{

    init {
        recvMessage()
    }

    companion object
    {
        var receivedMessage :ByteArray = ByteArray(1024)
    }


    fun sendMessage(data: ByteArray )
    {
        if(isConnected)
            Thread {
                val dataOutputStream = DataOutputStream(this.outputStream)
                dataOutputStream.write(data)
            }.start()
    }



    private fun recvMessage() = Thread{
        while(true)
        {
            if (isConnected) {
                inputStream.read(receivedMessage)
            }
        }
    }.start()

    fun getMessage():ByteArray
    {
        return receivedMessage;
    }

}

To use this client I have MyApplication class as shown here

In the app startup the client get configured (connects to server)

then I move to login activity there I send a login request to the server and get an answer this is the login button function

fun login(view: View)
{
        val username = findViewById<EditText>(R.id.username).text.toString()
        val password = findViewById<EditText>(R.id.password).text.toString()

        (this.application as MyApplication).client.sendMessage(PacketFactory.loginRequest(username, password))
        val serverResponse = (this.application as MyApplication).client.getMessage()
        val buf : ByteBuffer = ByteBuffer.wrap(serverResponse)

        println()
        println("got:" + Message.getRootAsMessage(buf).data)
        println()


}

The problem is that at the first click I get null then the msg I needed before (a click before)

Any help for those more experienced would be most appreciated. I'm at the end of my skills here... need some guidance, please!

Eyal Elbaz
  • 31
  • 9

1 Answers1

0

fixed: I added messages stack

package com.trivia_app
import java.io.DataOutputStream
import java.net.Socket
import java.util.*

class Client : Socket()
{

    init {
        recvMessage()
    }

    companion object
    {
        var pendingMessages : Stack<ByteArray> = Stack()
    }


    fun sendMessage(data: ByteArray )
    {
        if(isConnected)
            Thread {
                val dataOutputStream = DataOutputStream(this.outputStream)
                dataOutputStream.write(data)
            }.start()
    }



    private fun recvMessage() = Thread{
        val message = ByteArray(1024)
        while(true)
            if (isConnected)
                if (inputStream.read(message) > 0)
                    pendingMessages.push(message)
    }.start()

    fun getMessage():ByteArray
    {
        while (pendingMessages.empty());
        return pendingMessages.pop()
    }

}

Eyal Elbaz
  • 31
  • 9