所以我們在課堂上與ServerSockets混合在一起,製作了一個非常簡單的HTTP服務器,它接受請求,不做任何事情,並以200 OK和一些HTML內容作爲響應。ServerSocket不能使用try-with-resources?
我一直在試圖找出這個問題兩天,我一直沒有得到處理它,也沒有我的老師。我認爲這是關閉服務器的問題,出於某種奇怪的原因。我已經解決了這個問題,但只是想知道爲什麼我首先發生了。
這裏有三個片段:
HttpServer.class:
package httpserver;
import java.io.Closeable;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class HttpServer implements Closeable {
public static final int PORT = 80;
public static final int BACKLOG = 1;
public static final String ROOT_CATALOG = "C:/HttpServer/";
private ServerSocket server;
private Socket client;
private Scanner in;
private PrintWriter out;
private String request;
public HttpServer() throws IOException {
server = new ServerSocket(PORT, BACKLOG);
}
public Socket accept() throws IOException {
client = server.accept();
in = new Scanner(client.getInputStream());
out = new PrintWriter(client.getOutputStream());
return client;
}
public void recieve() {
request = in.nextLine();
System.out.println(request);
}
public void respond(final String message) {
out.print(message);
out.flush();
}
@Override
public void close() throws IOException {
if(!server.isClosed()) {
client = null;
server = null;
}
}
}
Main.class解決方案,工作:
package httpserver;
import java.io.IOException;
import java.net.Socket;
public class Main {
public static void main(String[] args) throws IOException {
HttpServer server = new HttpServer();
Socket client;
while(true) {
client = server.accept();
server.recieve();
server.respond("HTTP/1.0 200 OK\r\n"
+ "Content-Type: text/html\r\n"
+ "\r\n"
+ "<html><body><b>hello..</b></body></html>");
client.close();
}
}
}
Main.class解決方案,沒有按沒有工作:
package httpserver;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try(HttpServer server = new HttpServer()) {
while (true) {
server.accept();
server.recieve();
server.respond("HTTP/1.0 200 OK\r\n"
+ "Content-Type: text/html\r\n"
+ "\r\n"
+ "<html><body><b>hello..</b></body></html>");
}
} catch(IOException ex) {
System.out.println("We have a problem: " + ex.getMessage());
}
}
}
我能想象它是與每次循環迭代後不關閉客戶端套接字。但即便如此,在這種情況下,至少應該經歷一次。我真的不明白這個問題應該是什麼。
任何錯誤消息,沒什麼......
@ G-Man'Closeable'擴展'AutoCloseable',所以不是。 – 2013-03-06 13:57:16
您是否嘗試過調試您的代碼? – christopher 2013-03-06 14:00:55
@ChrisCooney我試過了,但我很不確定如何調試這樣的東西。在某些場合,NetBeans調試器並不是世界上最友好的調試器。 – Volatile 2013-03-06 14:05:42