java - 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 然后是我之前需要的味精(之前点击)
对那些更有经验的人的任何帮助将不胜感激。我在这里的技能已经结束了……需要一些指导,拜托!
解决方案
固定:我添加了消息堆栈
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()
}
}
推荐阅读
- python - 如何等到我使用 Python 套接字接收数据?
- javascript - Blueimp jQuery File Upload - 上传长列表问题
- spring - Spring Security 测试会话超时
- move - 将特定文件从多个文件夹移动到一个文件夹
- c# - 将字符串解析为可识别数据结构的最佳方法
- react-native - 如何在本机反应中动态更改高度视图?
- linux - 致命错误:asm/types.h:交叉编译内核 3.16 时没有这样的文件或目录
- awk - awk 问题中的 Switch/Case 语句
- sql - 如何使用具有相似但不相同的名称列连接 2 个表?
- docker - 在 Jenkins 中找不到 package.json