Web服务器大家应该都很熟悉了,web服务器的原理可以看这里。讲的挺详细的。
本篇主要是模拟一下简单的交互,通过socket通道,浏览器发送请求,服务器返回资源。
简单图例如上,然后来看代码吧
1、首先启动服务监听端口,使用线程池来完成交互
package server;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class HttpServer {
public static void main(String[] args) throws Exception {
//启动服务器,监听8080端口
ServerSocket server = new ServerSocket(8080);
System.out.println("服务器启动,监听8080端口");
ExecutorService pool = Executors.newCachedThreadPool();
//线程未间断一直监听客户端
while(!Thread.interrupted()){
Socket client = server.accept();
pool.execute(new ServerThread(client));
//new Thread(new ServerThread(client)).start();
}
server.close();
}
}
2、ServerThread做交互处理
package server;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class ServerThread implements Runnable{
//消息头Content-Type
private static Map<String,String> contentMap = new HashMap<String,String>();
private static String rootPath = "d:\\webroot\\";
static{
contentMap.put("html", "text/html;charset=utf-8");
contentMap.put("jpg", "image/jpeg");
}
private Socket client;
private InputStream in;
private OutputStream out;
public ServerThread(Socket client){
this.client = client;
init();
}
private void init() {
try {
in = client.getInputStream();
out = client.getOutputStream();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
doTask();
} catch (Exception e) {
e.printStackTrace();
}
}
private void doTask() throws Exception{
BufferedReader inReader = new BufferedReader(new InputStreamReader(in));
String inLine = inReader.readLine().split(" ")[1].replace("/", "\\");
if(inLine.equals("\\favicon.ico")){
return;
}
if(inLine.equals("\\")){
inLine+="index.html";
}
System.out.println("客户端请求:"+inLine);
//响应
InputStream inf = new FileInputStream(new File(rootPath+inLine));
PrintWriter pw = new PrintWriter(out);
pw.println("HTTP/1.1 200 OK");
String contentType = contentMap.get(inLine.substring(inLine.lastIndexOf(".")+1,inLine.length()));
//System.out.println(contentType);
pw.println("Content-Type:"+contentType);
pw.println("Content-Length:"+inf.available());
pw.println("Date:"+new Date());
pw.println("");
pw.flush();
byte[] buff = new byte[1024];
int len = 0;
while((len = inf.read(buff)) != -1){
out.write(buff, 0, len);
}
pw.flush();
inf.close();
pw.close();
inReader.close();
client.close();
}
}
通过Socket输入流获得请求消息头,解析请求的资源,然后在本地新建webroot目录存放资源。然后读取资源通过socket输出流响应到浏览器。
3、操作
webroot下的资源
index.html内容如下:
浏览器访问localhost:8080
服务端日志
源码下载