【发布时间】:2016-07-20 08:08:51
【问题描述】:
我目前正在使用套接字处理一个小的客户端/服务器任务。
可悲的是,当客户端应该读取服务器发送的“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();
}
}
【问题讨论】:
-
似乎没有建立连接。你的
output实例是什么? -
与服务器上的相同。我也在那里使用 PrintWriter。