java socket 自写静态服务器 apache

需要在F盘下创建ooo文件夹,html页面放置其中  就可以在浏览器中访问    此端口监听 8080

package cn.com.test09;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class t14 {

    public static void main(String[] args) {
        try {
            ServerSocket ss= new ServerSocket(8080);
            while(true){
                Socket soc = ss.accept();
                new Thread(new ServerB(soc)).start();
            }
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
class ServerB implements Runnable{
    private Socket soc;
    private BufferedReader br;
    private PrintWriter dos;
    String html ;
    ServerB(Socket soc){
        this.soc=soc;
        try {
            br=new BufferedReader(new InputStreamReader(soc.getInputStream()));
            dos= new PrintWriter(soc.getOutputStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    private String[] getHtml(String str,String split){
        return str.split(split);
        
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        String s;
        try {
            String one = br.readLine();
            if(!(one.equals("GET /favicon.ico HTTP/1.1"))){
                
                 html =getHtml(getHtml(one," ")[1],"\\?")[0];
                
                 File f= new File("F:/ooo"+html);
                    InputStream in= new FileInputStream(f);
                    byte[] b= new byte[(int) f.length()];
                    in.read(b);
                    dos.write(new String(b));
                    dos.flush();
                    System.out.println(b);
//                    OutputStream ssss = soc.getOutputStream();
                    System.out.println("===========");
//                    ssss.write(b);
//                    ssss.flush();
                    in.close();
            }
            
            
            br.close();
        
            dos.close();
            //ssss.close();
            soc.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
    
}

 

posted @ 2014-04-14 16:50  家徒四壁全是伤  阅读(229)  评论(0编辑  收藏  举报