如何使用RxJava发送字节流?



有这样一个代码,它完美地将字符串传输到服务器并读取响应字符串。

val thread = Thread {
try {
val port = 8888
println("Try to open connection:$port")
val socket = Socket("192.168.0.104", port)
println("Connection is created")
val pw = PrintWriter(socket.getOutputStream(), true)
val br = BufferedReader(InputStreamReader(socket.getInputStream()))
pw.println("Hello from client 1")
Log.e("Server answer", br.readLine())
pw.close()
br.close()
socket.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
thread.start()

我正在尝试使用RxJava

做同样的事情
fun connectToServer() {
val TAG = "Server answer"
connectToServerWrapper()
.observeOn(Schedulers.io())
.subscribeBy (onSuccess = {
Log.e(TAG, it)
}, onError = {
Log.e(TAG, it.toString())
})
.addTo(compositeDisposable)
}
fun connectToServerWrapper(): Single<String> {
return Single.create { emitter ->
val port = 8888
println("Try to open connection:$port")
val socket = Socket(SERVER_IP, port)
println("Connection is created")
val pw = PrintWriter(socket.getOutputStream(), true)
val br = BufferedReader(InputStreamReader(socket.getInputStream()))
pw.println("Hello from client 1")
emitter.onSuccess(br.readLine())
pw.close()
br.close()
socket.close()
}
}

Android.os。NetworkOnMainThreadException在onError()中出现。我做错了什么?

你不应该在主线程中执行网络请求

fun connectToServer() {
val TAG = "Server answer"
connectToServerWrapper()
.subscribeOn(Schedulers.io())
.subscribeBy (onSuccess = {
Log.e(TAG, it)
}, onError = {
Log.e(TAG, it.toString())
})
.addTo(compositeDisposable)
}

相关内容

  • 没有找到相关文章

最新更新