gpt4 book ai didi

java - Kotlin BufferedReader.readLine() 导致无限循环

转载 作者:行者123 更新时间:2023-12-01 19:57:42 25 4
gpt4 key购买 nike

我正在用 Kotlin 制作简单的客户端-服务器应用程序。我遇到了 BufferedReader.readLine() 的问题。我的服务器发送了几行文本,在读取它们后,BufferedReader 会阻止程序,使其无法继续运行。看起来它仍在等待输入。我不知道如何解决它。这是我的客户端代码:

package Client

import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.Socket

class ConnectionHandler(client : Socket) {
private val reader : BufferedReader = BufferedReader(InputStreamReader(client.getInputStream()))
private val writer : PrintWriter = PrintWriter(client.getOutputStream(), true)
private var running : Boolean = false

fun handle() {
running = true
while (running) {
read()
write()
}
}

private fun write(){
var intput: String? = readLine()
if (intput != null) {
writer.println(intput)
if(intput.toLowerCase() == "exit")
running = false
}
}

private fun read(){
var output : String? = "Server:"

while (output != null) {
println(output)
output = reader.readLine()
}
}
}

这是我的服务器代码:

package Server

import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.Socket


class ClientHandler(private val client : Socket) {
private val reader : BufferedReader = client.getInputStream().bufferedReader()
private val writer : PrintWriter = PrintWriter(client.getOutputStream(), true)
private var running : Boolean = false

fun handle(){
running = true
writer.println("Welcome to Server")
writer.println("Possible operations: + - / *")
writer.println("Example input 1 + 2 (notice the spaces between signs)")
writer.println("To Exit write EXIT")


while (running){
try {
val text = reader.readLine()
if (text.toLowerCase() == "exit"){
shutdown()
continue
}
val values = text.split(" ")
val result = Calculator().calculate(values[0].toInt(), values[2].toInt(), values[1])
writer.println(" = $result" )
}catch (ex: Exception){
writer.println("Something went wrong, need to exit")
shutdown()
}
}

}

private fun shutdown(){
running = false;
writer.println("exit")
client.close()
println("${client.inetAddress.hostAddress} closed connection")
}

}

客户端读取最后一行“To Exit write EXIT”,然后等待,不接受输入。

最佳答案

readLine() 将阻塞并等待输入,并且仅当套接字关闭时才会返回 null。您需要调整客户端/服务器通信协议(protocol),以便服务器在完成写入时发送一个特殊标记,而客户端在收到该标记时退出 read 函数中的循环。

关于java - Kotlin BufferedReader.readLine() 导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49011480/

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