gpt4 book ai didi

Java Sockets - 挂起从服务器读取数据

转载 作者:行者123 更新时间:2023-12-01 10:07:33 25 4
gpt4 key购买 nike

我目前正在使用套接字执行一个小的客户端/服务器任务。遗憾的是,当客户端应该读取服务器发送的“200 OK File Created”时,客户端挂起。有什么是我忽略的吗?

客户:

public HTTPClient(InetAddress adress, int portnumber, String filename) throws IOException {
socket = new Socket(adress, portnumber);
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new PrintWriter(socket.getOutputStream());
this.filename = filename;
}

public void sendPutRequest() throws IOException {
output.println("PUT /" + filename + " HTTP/1.0");
output.flush();
File myFile = new File(this.filename);
if (myFile.exists()) {
for (String string : Files.readAllLines(myFile.toPath())) {
output.println(string);
}
output.flush();
String line;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
} else {
throw new IOException("File not found");
}
}

服务器:

  try (Socket client = this.socket.accept(); 
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream())) {

String lineIn = in.readLine();
if (lineIn.contains("PUT")) {
String filename = lineIn.split(" ")[1].substring(1);
List<String> filedata = new ArrayList<>();
String line;
while ((line = in.readLine()) != null) {
filedata.add(line);
System.out.println(line);
}
writeToFile(filename, filedata);
out.println("200 OK File Created");
out.flush();
}
}

最佳答案

您的服务器正在从连接中读取数据,直到连接关闭为止(仅在这种情况下,in.readLine() 才会返回 null)。

但是您的客户端不会关闭与服务器的连接。因此服务器陷入了 while 循环。

解决方案:发送请求后必须关闭output流。或者,在服务器端检测请求的结束,而无需等待“流结束”限制。

关于Java Sockets - 挂起从服务器读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36340730/

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