基于上一篇博客继续 往下写。本篇博客我们正式开始写一个简单版本的服务器。
1. 思考
我们需要考虑服务器应该具备哪些能力。首先,我们需要一个socket程序接收客户端请求;然后,我们需要给客户端一个返回;最后,我们需要包装一下http消息中携带的参数提供给使用了我们的服务器的上层程序。
2. 手写一个简单服务器
2.1 HttpRequest
package com.zlyx.easy.server.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class HttpRequest {
private String method;
private String url;
public HttpRequest(InputStream in) throws IOException {
InputStreamReader isReader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(isReader);
String string = bufferedReader.readLine();
String[] httpInfos = string.split(" ");
this.method = httpInfos[0];
this.url = httpInfos[1];
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
2.2 HttpResponse
package com.zlyx.easy.server.http;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
public class HttpResponse {
public BufferedWriter writer;
public HttpResponse(OutputStream os) {
writer = new BufferedWriter(new OutputStreamWriter(os));
}
public void write(String content) throws IOException {
writer.append("HTTP/1.1 200 OK\n").append("Content-Type: text/html\n").append("\r\n").append("<html><body>")
.append(content).append("</body></html>");
writer.flush();
}
}
2.3 HttpServlet
package com.zlyx.easy.server.servlet;
import java.io.IOException;
import java.net.Socket;
import com.zlyx.easy.server.http.HttpRequest;
import com.zlyx.easy.server.http.HttpResponse;
public class HttpServlet {
private HttpRequest request;
private HttpResponse response;
public HttpServlet(Socket socket) throws IOException {
request = new HttpRequest(socket.getInputStream());
response = new HttpResponse(socket.getOutputStream());
}
/**
* 处理get请求
*
* @throws IOException
*/
public void doGet() throws IOException {
System.out.println(request.getUrl());
response.write(String.valueOf(request.hashCode()));
}
}
2.4 MainServer
package com.zlyx.easy.server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import com.zlyx.easy.server.servlet.HttpServlet;
public class MainServer {
/**
* server port
*/
private static int port = 8080;
public static void main(String[] args) throws IOException {
ServerSocket ss = null;
try {
ss = new ServerSocket(port);
while (true) {
Socket socket = ss.accept();
while (true) {
new HttpServlet(socket);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
ss.close();
}
}
}
启动ManServer后通过浏览器访问http://localhost:8080/,控制台输出:
浏览器输出:
一个简单的服务器就写出来了。