[英]How can i read text from socket Kotlin/Android?
I will say right away that I started to study Kotlin recently, and I just want to rewrite one program, and therefore I took up this马上就说最近开始研究Kotlin,只是想重写一个程序,所以接了这个
I want to read the text received from the incoming stream, but as a result, I get the following我想阅读从传入的 stream 收到的文本,但结果,我得到以下
Perhaps I make terribly stupid mistakes, but I hardly understand what and how it works here (I read half Internet)也许我犯了非常愚蠢的错误,但我几乎不明白它在这里是什么以及它是如何工作的(我读了一半的互联网)
I don't know what is this我不知道这是什么
PS I already tried to use this, but the program just doesn't go further and that's it PS我已经尝试过使用它,但程序只是没有进一步 go 就是这样
package com.example.appisone
import java.net.Socket
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import kotlinx.coroutines.*
import java.io.InputStreamReader
import java.util.*
class MainActivity : AppCompatActivity() {
private var Text_Edit: EditText? = null
private var btn: Button? = null
private var Text_view: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Text_Edit = findViewById(R.id.EditText)
btn = findViewById(R.id.Button)
Text_view = findViewById(R.id.TextView)
btn?.setOnClickListener {
Text_view?.text = Text_Edit?.text
println("Button is pressed!")
GlobalScope.launch(Dispatchers.IO) {
send_text()
}
}
}
private fun send_text() {
var data: Any
println("send_text is pressed!")
val client = Socket("192.168.0.3", 9090)
val text = Text_Edit?.text.toString()
println(text.toByteArray())
client.getOutputStream().write(text.toByteArray())
val reader = client.getInputStream()
data = reader.toString()
println("Сообщение --- >$data")
}
} ```
Thanks in advance for your wasted time
You don't read from a Reader
like this:您不会像这样从
Reader
中阅读:
reader.toString()
That just renders the Reader
>>object<< as a string.这只是将
Reader
>>object<< 呈现为字符串。 Since toString
has not been overridden by Reader
, you get the Object::toString
implementation.由于
toString
尚未被Reader
覆盖,因此您将获得Object::toString
实现。 (It prints the internal class name and the object's "identity hash code" in hexadecimal.) (它以十六进制打印内部 class 名称和对象的“身份 hash 代码”。)
To read from a Reader
use one of the read
methods in the Reader API , or wrap it in a Scanner
or a BufferedReader
so that you can use those APIs.要从
Reader
读取,请使用Reader API中的一种read
方法,或将其包装在Scanner
或BufferedReader
中,以便您可以使用这些 API。
In your "PS" you are also calling toString() on an object that doesn't override toString().在您的“PS”中,您还在不覆盖 toString() 的 object 上调用 toString()。 Based on the class name, it looks like it is a byte[].
根据 class 名称,它看起来像是一个 byte[]。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.