晚上好,我來到這裏這個服務器發送命令到HTTP服務器
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicInteger;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class Test {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/test", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
AtomicInteger atomicInteger = new AtomicInteger(0);
int theValue = atomicInteger.get();
@Override
public void handle(HttpExchange t) throws IOException {
String response = String.format("Besuche: %d%n", atomicInteger.addAndGet(1));
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
它的每次訪問我的網站上做現在http://localhost:8000/test 計數我有一個客戶端,它顯示我的服務器在我的控制檯內容。
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL test = new URL("http://localhost:8000/test");
URLConnection connect = test.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
我希望客戶端向服務器發送一個重置服務器上計數器的命令。我可以找到這個here,但我不知道如何在我的情況下實現這一點。我希望有人能夠解釋我現在可以做什麼。
我試圖處理它在同一路徑上,但它將如何復位?如果我刷新它仍然計數,但不重置任何東西。我如何發佈比什麼? –
@SebastianKawa在答案的底部看到編輯 –
令人敬畏的工作。謝啦。我剛剛得到的問題是,如果我將它重置爲0,它將從2開始計數。我將試着找出原因。如果你有任何提示,歡迎你。 –