首页 > 解决方案 > inputStream 空延迟 Kotlin

问题描述

您好,我正在 android studio 中编写客户端应用程序

这是我的客户类:


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;
    }

}

要使用这个客户端,我有 MyApplication 类,如下所示

在应用程序启动中,客户端被配置(连接到服务器)

然后我转到登录活动那里我向服务器发送登录请求并得到答案这是登录按钮功能

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()


}

问题是在第一次点击时我得到 null 然后是我之前需要的味精(之前点击)

对那些更有经验的人的任何帮助将不胜感激。我在这里的技能已经结束了……需要一些指导,拜托!

标签: javaandroidkotlin

解决方案


固定:我添加了消息堆栈

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()
    }

}


推荐阅读