java - inputStream null 延迟 Kotlin

标签 java android 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 类,如图所示 here

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

然后我进入登录 Activity ,向服务器发送登录请求并得到答案 这是登录按钮功能

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,然后是我之前需要的消息(之前单击)

对于那些更有经验的人的任何帮助将不胜感激。我的技能已经结束了...需要一些指导,请!

最佳答案

已修复: 我添加了消息堆栈

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

}

关于java - inputStream null 延迟 Kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62171163/

相关文章:

java - 如何使用流将二维 int 数组转换为单个字符串?

intellij-idea - 安装 IntelliJ IDEA 后从控制台运行一个简单的 hello world

android - 条件链单一且可完成

java - DecimalFormat 被服务器设置覆盖

java - 请解释一下这行代码 a[s1.charAt(i) - 'a' ]++;

java - 适用于TreeSet无区分字段时的比较器

android - 在尽我所能后,Android中仍然存在针对opencv的 “Could not find OpenCV Library - 2.4.9.apk”错误

android - 迁移到Gradle插件3.2.1

android - 平板电脑上类似 Google Now 的不对称网格

android - 如何更改 alertdialog 上肯定按钮的颜色?