使用Socket模拟简易Web服务器

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

服务端日志

源码下载

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值