java编写一个服务器

版权声明:本文纯属作者口胡,欢迎转载 https://blog.csdn.net/TQCAI666/article/details/88957386

WebServer.java

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class WebServer {
    public static final int HTTP_PORT=8081;
    private ServerSocket serverSocket;
    public void startServer(int port){
        try{
            serverSocket=new ServerSocket(port);
            System.out.println("web server startup on "+port);
            while (true){
                Socket socket=serverSocket.accept();
                // 通过线程的方式处理客户端请求
                new Processor(socket).start();
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] argv) throws Exception{
        WebServer server=new WebServer();
        if(argv.length==1){
            server.startServer(Integer.parseInt(argv[0]));
        }else {
            server.startServer(WebServer.HTTP_PORT);
        }
    }
}

Processor.java

import java.io.*;
import java.net.Socket;

public class Processor extends Thread{
    private PrintStream out;
    private InputStream input;
    public static final String WEB_ROOT="/home/tqc/IdeaProjects/webServer/home";
    public Processor(Socket socket){
        try{
            input=socket.getInputStream();
            out=new PrintStream(socket.getOutputStream());
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    public void run(){
        try{
            String fileName=parse(input);
            readFile(fileName);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    public String parse(InputStream input) throws IOException{
        BufferedReader in=new BufferedReader(new InputStreamReader(input));
        String inputContent=in.readLine();
        //todo: 对于没有内容的异常处理,状态码400
        //分析HTTP信息,分析客户想访问哪个文件
        String request[]=inputContent.split(" ");
        //todo: 不为3段的异常处理,状态码400
        //请求方法
        String method=request[0];
        String fileName=request[1];
        String httpVersion=request[2];
        return fileName;
    }
    public void readFile(String fileName) throws IOException{
        File file=new File(Processor.WEB_ROOT+fileName);
        if(!file.exists()){
            //todo : 404
            return;
        }
        InputStream in=new FileInputStream(file);
        byte content[]=new byte[(int)file.length()];
        in.read(content);
        in.close();
        out.println("HTTP/1.1 200 sendFile");
        out.println("Content-length: "+content.length);
        out.println();
        out.write(content);
        out.flush();
        out.close();
    }
}

猜你喜欢

转载自blog.csdn.net/TQCAI666/article/details/88957386