简单tomcat实现

具体思路:

1.使用socket做服务端,并监听9090端口,等待客服端的登陆请求的访问(每个请求做成一个线程,提交到线程池中运行)。

2.拼接好请求url,并使用浏览器去访问这个链接

3.把serverSocket.accept();得到的对象封装为MyRequest、MyResponse对象,进行用户信息比对,返回登陆结果。

socket服务端:Server.java

package service;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 服务请求类
 *
 */
public class Server {

    private static ExecutorService serviceThreadPool = Executors.newFixedThreadPool(20);

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        try {
            serverSocket = new ServerSocket(9090);
            while (true) {
                socket = serverSocket.accept();//这里还有很多优化的地方,线程池的设置和接收的方式等
                serviceThreadPool.submit(new SocketacceptRunnable(socket));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

把接收到的 serverSocket.accept(); 对象中请求的流转为字符串,这样我们就能看到请求的格式和字符,这样方便截取请求的url和url中传过来的参数:

MyRequest.java:

package service;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class MyRequest {
    private final Socket socketAccpet;
    private StringBuilder builder = new StringBuilder();
    private InputStream in = null;

    public MyRequest(Socket socketAccpet) {
        this.socketAccpet = socketAccpet;
    }

    public String getRequestAllString() throws IOException {
        in = this.socketAccpet.getInputStream();
        byte[] buff = new byte[1024];
        int length = 0;
        if ((length = in.read(buff)) > 0) {
            builder.append(new String(buff, 0, length));
        }

        System.out.println("接收到请求:" + builder.toString());
        return builder.toString();
    }

    public String getURL() throws IOException {
        String allStr = getRequestAllString();
        if (allStr.indexOf("HTTP/1.1") != -1) {
            return allStr.substring(allStr.indexOf("/"), allStr.indexOf("HTTP/1.1") - 1);
        } else {
            return "";
        }
    }
}

MyResponse.java

package service;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class MyResponse {
    private final Socket socketAccpet;
    private StringBuilder builder = null;
    OutputStream out = null;

    public MyResponse(Socket socketAccpet) {
        this.socketAccpet = socketAccpet;
    }

    public void setResponseStr(StringBuilder builder) {
        this.builder = builder;
    }

    public void writeStr(String str) throws IOException {
        out = this.socketAccpet.getOutputStream();
        OutputStreamWriter streamWriter = new OutputStreamWriter(out);
        streamWriter.write(str);
        streamWriter.flush();
        out.close();
        streamWriter.close();
    }
}

登录的处理类:LoginHttp.java

package service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;


public class LoginHttp {
    private String name;
    private String pwd;
    public void service(MyRequest request,MyResponse response){
        Calendar calendar = Calendar.getInstance();
        try {
            String urlStr = request.getURL();

            String[] params = urlStr.substring(urlStr.indexOf("?")+1).split("&");
            for (int i = 0; i < params.length; i++) {
                String[] info = params[i].split("=");
                if ("name".equals(info[0])) {
                    this.name = info[1];
                } else if ("pwd".equals(info[0])) {
                    this.pwd = info[1];
                }
            }

            if ("abc".equals(name) && "123abc".equals(pwd)) {
                response.writeStr("登陆成功:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime()));
            } else {
                response.writeStr("登陆失败:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime()));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

每次请求都是应该线程:SocketacceptRunnable.java

package service;


import java.net.Socket;

public class SocketacceptRunnable implements Runnable {

    private final Socket socketAccpet;

    public SocketacceptRunnable(Socket socketAccpet) {
        this.socketAccpet = socketAccpet;
    }

    @Override
    public void run() {
        try {
//          BufferedReader bufferedReader = new BufferedReader(new FileR);
            MyRequest myRequest = new MyRequest(socketAccpet);
            System.out.println(myRequest.getRequestAllString());//先让MyRequest中的builder属性赋值
            LoginHttp http = new LoginHttp();//请求处理类,这个可以做成配置
            MyResponse response = new MyResponse(socketAccpet);
            http.service(myRequest, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

测试:

运行Server.java:

在IE浏览器中访问连接:http://localhost:9090/myhello?name=abc&pwd=123abc

image

你可能感兴趣的:(简单tomcat实现)