赞
踩
1、代码如下
package com.httpserver.server; import java.io.*; import java.net.Socket; import java.util.Date; import java.util.HashMap; import java.util.Map; public class ServerThread implements Runnable { private static Map<String,String> contentMap = new HashMap<>(); static { contentMap.put("html","text/html;charset=utf-8"); contentMap.put("jpg","image/jpeg"); } private Socket client; private InputStream ins; private OutputStream out; private PrintWriter pw; private BufferedReader br; public ServerThread(Socket client){ this.client = client; init(); } private void init(){ try { ins = client.getInputStream(); out = client.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { try { go(); } catch (IOException e) { e.printStackTrace(); } } private static final String webroot = "e:\\webroot\\"; private void go() throws IOException { //读取去请求内容 BufferedReader reader = new BufferedReader(new InputStreamReader(ins)); String line = reader.readLine().split(" ")[1].replace("/","\\"); //请求的资源 System.out.println(line); if(line.equals("\\")){ line += "index.html"; } //给用户响应 PrintWriter pw = new PrintWriter(out); //文件在e:\webroot\index.html下 InputStream i = new FileInputStream(webroot + line); // BufferedReader fr = new BufferedReader(new InputStreamReader(i)); pw.println("HTTP/1.1 200 OK"); String s = line.substring(line.lastIndexOf(".")+1,line.length()); System.out.println(s); pw.println("Content-Type: "+contentMap.get(s)); pw.println("Content-Length: " +i.available()); pw.println("Server: Hello" ); pw.println("Data:" + new Date()); pw.println(); pw.flush(); byte[] buff = new byte[1024]; int leg = 0; while ((leg = i.read(buff)) != -1){ out.write(buff,0,leg); } pw.flush(); i.close(); pw.close(); reader.close(); client.close(); } }
2、测试代码
package com.httpserver.server; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class HttpServer3 { public static void main(String[] args) throws IOException { ExecutorService pool = Executors.newCachedThreadPool(); //启动服务器,监听8888端口 ServerSocket server = new ServerSocket(8888); System.out.println("服务器启动,监听" + 8888 + "端口。"); while (!Thread.interrupted()){ //不接收接收客户端请求 Socket client = server.accept(); pool.execute(new ServerThread(client)); } server.close(); } }
3、文件目录结构
(1)index.html的文件内容如下:
(2)login.html的文件内容如下:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。