The basics of HTTP are fairly simple. Open a ServerSocket to listen for incoming requests. When a connection is made, start a new thread and send the response. That could look like,
public static void main(String[] args) {
try {
ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(8080, 10);
StringBuilder body = new StringBuilder();
body.append("<html><body><h1>Hello, World!</h1></body></html>");
while (true) {
Socket s = ss.accept();
Thread t = new Thread(new HttpReply(s, body));
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Then to actually send the response you get an OutputStream from the Socket and write the required HTTP headers and then the body. Like,
发布评论
评论(1)
HTTP 的基础知识相当简单。打开 ServerSocket 来侦听传入请求。建立连接后,启动一个新线程并发送响应。这可能看起来像,
然后要实际发送响应,您从
Socket
获取OutputStream
并写入所需的 HTTP 标头,然后写入正文。就像,它将在您的计算机的端口
8080
上侦听请求并使用基本的 hello world 网页进行回复。The basics of HTTP are fairly simple. Open a
ServerSocket
to listen for incoming requests. When a connection is made, start a new thread and send the response. That could look like,Then to actually send the response you get an
OutputStream
from theSocket
and write the required HTTP headers and then the body. Like,Which will listen on port
8080
of your machine for requests and reply with a basic hello world web page.