1.设计思路
这是一个只能访问静态资源的简易Tomcat
2.代码实现
public class Server {
public Server(int port,String address) {
this.prot = port;
this.address = address;
}
public Server(int port) {
this.prot = port;
}
public Server(String address) {
this.address = address;
}
public Server() {
}
//初始目录
private final String ROOT = System.getProperty("user.dir")+File.separator+"webapps";
//监听地址
private String address ="127.0.0.1";
//监听端口
private int prot=8080;
public void await() {
ServerSocket server = null;
ThreadPoolExecutor pool = new ThreadPoolExecutor(10, 30, 30, TimeUnit.SECONDS, new LinkedTransferQueue<Runnable>());
try {
server = new ServerSocket(prot,30,InetAddress.getByName(address));
System.out.println("开始监听");
} catch (IOException e) {
e.printStackTrace();
System.err.println("ServerSocket 初始化出错");
}
while(true) {
try {
Socket socket = server.accept();
RequestHandler handler = new RequestHandler(socket.getInputStream(),socket.getOutputStream(),ROOT);
pool.execute(handler);
} catch (IOException e) {
e.printStackTrace();
System.err.println();
}
}
}
}
public class RequestHandler implements Runnable {
public RequestHandler(InputStream in,OutputStream out ,String root) {
this.in = in;
this.out=out;
this.ROOT=root;
}
// 默认访问路径
private static String url = "/ROOT/index.html";
private InputStream in = null;
private OutputStream out = null;
private String ROOT=null;
@Override
public void run() {
System.out.println("开始处理请求");
StringBuffer buffer = new StringBuffer();
byte[] b = new byte[2048];
int i;
try {
i = in.read(b);
for (byte c : b) {
buffer.append((char)c);
}
String temp = buffer.toString();
//正则匹配url
Pattern regx =Pattern.compile("\\s/\\S*\\s");
Matcher matcher = regx.matcher(temp);
if(matcher.find()) {
SendResponse send = new SendResponse(out,ROOT+matcher.group().trim());
send.send();
}else {
SendResponse send = new SendResponse(out,ROOT+url);
send.send();
}
} catch (IOException e) {
System.err.println("读取失败");
e.printStackTrace();
}finally {
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class SendResponse {
private String url;
private OutputStream out;
public SendResponse(OutputStream out, String url) {
this.out = out;
this.url = url;
}
public void send() throws IOException {
File file = new File(url);
// 判断请求文件是否存在,如果存在返回
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
byte[] temp = new byte[2048];
int endflag = in.read(temp);
while (endflag != -1) {
out.write(temp);
endflag = in.read(temp);
}
in.close();
// 如果不存在报404
} else {
out.write("404 file not found".getBytes("utf8"));
System.out.println("响应成功");
}
}
}
public class Main {
public static void main(String[] args) {
Server server = new Server();
server.await();
}
}
3.代码说明
开启服务端,默认监听8080端口,设置程序路径,循环监听用户请求,当用户发来请求,采用线程池中的线程去处理用户请求,通过正则匹配用户的访问目录 。
没有匹配到访问默认路径。将用户访问的文件读取出来,响应到浏览器 上。