http服务器: 大部分都是按行从网卡读和写,当读请求和响应里的body部分时,不能按行读,因为换行符可能是body里的一部分,写基本都是按行写. socket对象在最后需要关闭,关闭socket也将客户端和服务器端的相关流关闭了. http服务器代码:
import java.io.*;
import java.util.HashMap;
public class HttpRequest {
private String method;
private String url;
private String version ;
private HashMap<String, String> header=new HashMap<>();
private HashMap<String, String> shouhangjd=new HashMap<>();
private HashMap<String, String> cookie=new HashMap<>();
public static HttpRequest build(InputStream inputStream) {
HttpRequest httpRequest = new HttpRequest();
try{
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
String firstLine = bufferedReader.readLine();
String[] temp=firstLine.split(" ");
httpRequest.method = temp[0];
httpRequest.url = temp[1];
httpRequest.version = temp[2];
int tempIndex = httpRequest.url.indexOf("?");
if (tempIndex != -1) {
String parameters = httpRequest.url.substring(tempIndex + 1);
tempMethod(httpRequest.shouhangjd,parameters);
}
String headTemp=null;
while ((headTemp = bufferedReader.readLine()) != null && headTemp.length() != 0) {
String[] a=headTemp.split(": ");
httpRequest.header.put(a[0], a[1]);
}
String tempCookie=httpRequest.header.get("Cookie");
if (tempCookie != null) {
String[] a=tempCookie.split("; ");
for (String b: a
) {
String[] c=b.split("=");
httpRequest.cookie.put(c[0], c[1]);
}
}
if("POST".equalsIgnoreCase(httpRequest.getMethod())||"PUT".equalsIgnoreCase(httpRequest.getMethod())) {
int contentLength=Integer.parseInt(httpRequest.header.get("Content-Length"));
char[] content = new char[contentLength];
int len=bufferedReader.read(content);
String trueBody = new String(content, 0, len);
tempMethod(httpRequest.shouhangjd,trueBody);
}
} catch (IOException e) {
e.printStackTrace();
}
return httpRequest;
}
public static void tempMethod(HashMap<String,String> tempHashMap,String temp){
String[] a=temp.split("&");
for (String b:a
) {
String[] c = b.split("=");
tempHashMap.put(c[0], c[1]);
}
}
public String getMethod() {
return method;
}
public String getUrl() {
return url;
}
public String getVersion() {
return version;
}
public HashMap<String, String> getHeader() {
return header;
}
public HashMap<String, String> getShouhangjd() {
return shouhangjd;
}
public HashMap<String, String> getCookie() {
return cookie;
}
}
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class HttpResponse {
private String myVersion = "HTTP/1.1";
private String status;
private String miaoShu;
private HashMap<String, String> header=new HashMap<String,String>();
private StringBuilder body=new StringBuilder();
private OutputStream outputStream;
public void setHeader(String k, String v) {
this.header.put(k, v);
}
public void setBody(String string) {
this.body.append(string);
}
public void setOutputStream(OutputStream outputStream) {
this.outputStream = outputStream;
}
public void setMyVersion(String myVersion) {
this.myVersion = myVersion;
}
public void setStatus(String status) {
this.status = status;
}
public void setMiaoShu(String miaoShu) {
this.miaoShu = miaoShu;
}
public static HttpResponse build(OutputStream outputStream) {
HttpResponse httpResponse = new HttpResponse();
httpResponse.setOutputStream(outputStream);
return httpResponse;
}
public void flush(){
try {
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(this.outputStream));
bufferedWriter.write(myVersion +" "+ status +" "+ miaoShu+"\n");
int contentLength = this.body.toString().getBytes().length;
this.header.put("content-length" , contentLength+"");
for (Map.Entry<String, String> entry : this.header.entrySet()
) {
bufferedWriter.write(entry.getKey()+": "+entry.getValue()+"\n");
}
bufferedWriter.write("\n");
bufferedWriter.write(body.toString());
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class HttpSever {
private ServerSocket serverSocket = null;
public HttpSever(int port) throws IOException {
this.serverSocket = new ServerSocket(port);
}
public void start() throws IOException {
System.out.println("服务器启动");
ExecutorService executorService= Executors.newCachedThreadPool();
while (true) {
Socket socket = serverSocket.accept();
executorService.execute(new Runnable() {
@Override
public void run() {
try {
poccess(socket);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
private void poccess(Socket socket) throws IOException {
try{
HttpRequest httpRequest =HttpRequest.build(socket.getInputStream());
HttpResponse httpResponse = HttpResponse.build(socket.getOutputStream());
if ("GET".equalsIgnoreCase(httpRequest.getMethod())) {
doGet(httpRequest, httpResponse);
}
if ("POST".equalsIgnoreCase(httpRequest.getMethod())) {
dopost(httpRequest, httpResponse);
}
httpResponse.flush();
}catch (IOException e){
e.printStackTrace();
}finally {
socket.close();
}
}
private void dopost(HttpRequest httpRequest, HttpResponse httpResponse) {
if (httpRequest.getUrl().startsWith("/login")) {
String username = httpRequest.getShouhangjd().get("username");
String password = httpRequest.getShouhangjd().get("password");
if("liuheizi".equals(username)&&"123".equals(password)){
httpResponse.setStatus("200");
httpResponse.setMiaoShu("OK");
httpResponse.setHeader("Content-Type","text/html");
httpResponse.setHeader("Set-Cookie","username="+username);
httpResponse.setBody("<html>" + "\n");
httpResponse.setBody("<head><meta charset=UTF-8></head>"+"\n");
httpResponse.setBody("<div>欢迎您"+username+"</div>" + "\n");
httpResponse.setBody("</html>");
}else{
httpResponse.setStatus("403");
httpResponse.setMiaoShu("Forbidden");
httpResponse.setHeader("Content-Type","text/html,charset=utf-8");
httpResponse.setBody("<html>" + "\n");
httpResponse.setBody("<head><meta charset=UTF-8></head>"+"\n");
httpResponse.setBody("<div>账号或者密码错误,登录失败</div>" + "\n");
httpResponse.setBody("</html>");
}
}
}
private void doGet(HttpRequest httpRequest,HttpResponse httpResponse) throws IOException {
if (httpRequest.getUrl().startsWith("/index.html")) {
if (httpRequest.getCookie().get("username")==null) {
InputStream inputStream= HttpSever.class.getClassLoader().getResourceAsStream("index.html");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String temp=null;
while ((temp = bufferedReader.readLine()) != null) {
httpResponse.setBody(temp + "\n");
}
bufferedReader.close();
httpResponse.setStatus("300");
httpResponse.setMiaoShu("OK");
httpResponse.setHeader("Content-Type", "text/html;charset=utf-8");
}else{
httpResponse.setStatus("200");
httpResponse.setMiaoShu("OK");
httpResponse.setHeader("Content-Type", "text/html,charset=utf-8");
httpResponse.setBody("<html>");
httpResponse.setBody("<head><meta charset=UTF-8></head>"+"\n");
httpResponse.setBody("<div>您已经登录了</div>");
httpResponse.setBody("</html>");
}
}
}
public static void main(String[] args) throws IOException {
HttpSever httpSever = new HttpSever(9090);
httpSever.start();
}
}
html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>这是第一个页面</title>
</head>
<body>
<form method="post" action="/login">
<div style="margin-bottom: 5px">
<input type=text" name="username" placeholder="请输入姓名">
</div>
<div style="margin-bottom: 5px">
<input type="password" name="password" placeholder="请输入密码">
</div>
<div>
<input type="submit" value="登录">
</div>
</form>
</body>
</html>
|