用Socket编程来实现tomcat对于浏览器输入uri和显示对应的页面功能:此篇博客就用了一个TestSevlet类和两个html页即可实现;
下一篇博客:原生jdk实现tomcat功能+对比servletapi和tomcat执行流程分析 --动态版
我们要做的,是对于一个浏览器端访问产生的Socket的我们服务端ServerSocket拿到之后,用OutputStream写入其uri对应的html页即可,所以说逻辑很简单;下面是代码:
package cn.wcy.mytomcat1;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server1 {
//定义一个变量,存放服务端WebContent目录的绝对路径,System.getProperty("user.dir")得到的是此项目的路径
public static String WEB_ROOT=System.getProperty("user.dir")+"/"+"WebContent";
//定义静态变量,用于存放本次请求的静态页面名称
private static String url = "";
public static void main(String[] args) throws IOException {
// System.out.println(WEB_ROOT);
//创建ServerSocket,监听本机的80端口,等待来自客户端的请求
ServerSocket ss = null;
Socket socket = null;
OutputStream os = null;
InputStream is = null;
try {
ss = new ServerSocket(8080);
while(true) {
//获取到客户端对应的socket
socket = ss.accept();
//获取到输入流对象
is = socket.getInputStream();
//获取到输出流对象
os = socket.getOutputStream();
//获取HTTP协议的请求部分 ,截取客户端访问的资源名称,将这个资源名称赋值给url
parse(is);
//发送静态资源
sendStaticResource(os);
}
}catch(Exception e) {
e.printStackTrace();
}finally {
if(null!=is) {
is.close();
is = null;
}
if(null!=os) {
os.close();
os = null;
}
if(null!=socket) {
socket.close();
socket = null;
}
}
}
//获取HTTP协议的请求部分 ,截取客户端访问的资源名称,将这个资源名称赋值给url
private static void parse(InputStream is) throws IOException {
//定义一个变量,存放http协议请求部分数据
StringBuffer content = new StringBuffer(2048);
//定义一个数组,存放http协议请求部分数据
byte[] buffer = new byte[2048];
int i=-1;
i = is.read(buffer);
for(int j=0;jindex1) {
//获取字符串穿获取到本次请求资源的名称
url = content.substring(index1+2,index2);
}
}
}
//发送静态资源
private static void sendStaticResource(OutputStream os) throws IOException {
//定义一个字节数组,用于存放本次请求的静态资源的内容
byte[] bytes = new byte[2048];
//定义一个文件输入流,用户获取静态资源的内容
FileInputStream is = null;
try {
//创建文件对象File,代表本次要请求的资源
File file = new File(WEB_ROOT,url);
//如果是file对象存在证明无论是我们html的名字还是客户端输入的都没问题
if(file.exists()) {
//向客户端输出http协议的响应头和响应行
os.write("HTTP/1.1 200 OK\n".getBytes());
os.write("Server:apache-Coyote/1.1\n".getBytes());
os.write("Content-Type:text/html;charset=utf-8\n".getBytes());
os.write("\n".getBytes());
is = new FileInputStream(file);
int ch = is.read(bytes);
while(ch!=-1) {
os.write(bytes,0,ch);
ch = is.read(bytes);
}
}else {
//如果不存在我们就让显示404 not found
os.write("HTTP/1.1 404 not found\n".getBytes());
os.write("Server:apache-Coyote/1.1\n".getBytes());
os.write("Content-Type:text/html;charset=utf-8\n".getBytes());
os.write("\n".getBytes());
String errorMessage = "404 not found";
os.write(errorMessage.getBytes());
}
}catch(Exception e) {
e.printStackTrace();
}finally {
if(null!=is) {
is.close();
is = null;
}
}
}
}
html页中没有什么内容的
然后启动这个服务,浏览器端输入http://localhost:8080/staticfirst.html才能够正确访问到这个页面,或者是staticsecond.html如果输入别的则会 404 not found;
接轨这一篇的文章:原生jdk实现tomcat功能+对比servletapi和tomcat执行流程分析 --动态版;