IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> http服务器 -> 正文阅读

[网络协议]http服务器

http服务器:
大部分都是按行从网卡读和写,当读请求和响应里的body部分时,不能按行读,因为换行符可能是body里的一部分,写基本都是按行写.
socket对象在最后需要关闭,关闭socket也将客户端和服务器端的相关流关闭了.
http服务器代码:

import java.io.*;
import java.util.HashMap;

/**
 * @author :liuheizi
 * @date :Created in 2022/2/16 16:46
 * @description:反序列化构建请求
 * @modified By:
 * @version: 1.8.0_192
 */
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) {//处理header
                String[] a=headTemp.split(": ");
               httpRequest.header.put(a[0], a[1]);
            }
            String tempCookie=httpRequest.header.get("Cookie");//处理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())) {//处理body
                       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;

/**
 * @author :liuheizi
 * @date :Created in 2022/2/16 18:00
 * @description:序列化将响应转化为字符流
 * @modified By:
 * @version: 1.8.0_192
 */
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;

/**
 * @author :liuheizi
 * @date :Created in 2022/2/16 18:37
 * @description:http服务器
 * @modified By:
 * @version: 1.8.0_192
 */
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")) {//构造body
            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>
  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2022-02-19 01:33:50  更:2022-02-19 01:35:11 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/26 8:44:30-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码