gpt4 book ai didi

java - inputStream null 延迟 Kotlin

转载 作者:行者123 更新时间:2023-12-01 16:24:47 24 4
gpt4 key购买 nike

你好,我正在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com