我在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")
}
}
客户端读取最后一行"要退出写入EXIT"然后等待,剂量接受输入。
答案 0 :(得分:3)
readLine()
将阻塞并等待输入,并且仅在套接字关闭时才返回null
。您需要调整客户端/服务器通信协议,以便服务器在完成写入时发送特殊标记,并且客户端在接收到该标记时退出read
函数中的循环。