[英]ObjectStreams with sockets hang at server and client side java
[英]Java Sockets - Hang on reading data from server
我目前正在使用套接字来处理一个小的客户端/服务器任务。 可悲的是,当客户端应读取服务器发送的“ 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
流。 或者,在服务器端检测请求的结束,而无需等待“流的结束”限制。
在您的服务器代码中:
while ((line = in.readLine()) != null) {
filedata.add(line);
System.out.println(line);
}
writeToFile(filename, filedata); // getting to this line?
您的服务器永远不会进入writeToFile行,因为套接字连接仍处于打开状态,并且仍处于while循环中。 作为解决方案,请使用DataFetcher
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.