晚上好,我在这里买了这台服务器,
的HttpServer
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 httpServer {
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();
//NimServer nimserver = new NimServer(32778);
//nimserver.serve();
}
static class MyHandler implements HttpHandler {
AtomicInteger atomicInteger = new AtomicInteger(0);
int theValue = atomicInteger.get();
@Override
public void handle(final HttpExchange t) throws IOException {
final String response;
final String requestMethod = t.getRequestMethod();
if ("GET".equals(requestMethod)) {
response = String.format("Besuche: %d%n", atomicInteger.addAndGet(1));
}
else if ("POST".equals(requestMethod)) {
atomicInteger.set(0);
response = "Reset to 0";
}
else {
throw new IOException("Unsupported method");
}
t.sendResponseHeaders(200, response.length());
final OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
此客户端
HttpClient的
import java.net.*;
import java.io.*;
public class httpClient {
static int clientno = 0;
public static void main(String[] args) throws Exception {
System.out.println(clientno);
URL test = new URL("http://localhost:8000/test");
HttpURLConnection connect = (HttpURLConnection) test.openConnection();
connect.setRequestMethod("POST");
BufferedReader in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
现在我想将 int clientno 从客户端发送到服务器,服务器应该像++一样计算它并将其发送回客户端。我读了很多关于Dataoutputstream但是总是包含套接字。没有套接字可以做到吗?
答案 0 :(得分:1)
在服务器端,您处于" POST"的处理程序中你必须调用t.getRequestBody()
- 这将为你提供客户输入。使用BufferedReader
(如果基于文字 - Integer.valueOf(stream.readLine())
)或DataInputStream
(如果基于二进制 - stream.readInt()
),您可以阅读该数字。类似地,通过t.getResponseBody()
,您可以将输出输出到客户端并以类似的方式写入数字。
对于客户,HttpURLConnection
有getInputStream()
和getOutputStream()
,您需要在服务器中以clientNumber
的方式编写$PYTHON_HOME/Libs/site-packages
。