客户端/服务器V_5.0

本次改动:

    调整结构,在http包中定义一个类HttpResponse,使用这个类的每个实例表示一个具体的响应。

    将ClientHandler中原本客户端的内容移动到HttpResponse中。

 package com.webserver.core;

 import  java.io.InputStream;

 import  java.net.ServerSocket;

 import  java.net.Socket;

//WebServer

public class WebServer{

    private ServerSocket server;

  //构造方法用于初始化WebServer

    public WebServer(){

    try{

    System.out.println("正在初始化服务端....");

    server=new ServerSocket(8080);

    System.out.println("服务端初始化完毕!");

   }catch(Exception e){

    e.printStackTrace();}}

    //服务端开始工作的方式

    try{

        System.out.println("等待客户端连接....");

        Socket socket=server.accept();

        System.out.println("一个客户端连接了!..");

         //启动一个线程处理该客户端

         ClientHandler handler=new ClientHandler(socket);

         Thread t=new Thread(handler);

         t.start();

       }catch(Exception e){

        e.printStackTrace();}}

    public static void main(String[] args){

        WebServer server=new WebServer();

        server.start();

        }

 ------------------------------------------------------------------

package com.webserver.core;

import java.io.File;

import java.net.Socket;

import com.webserver.httpRequest;

import com.webserver.httpResponse;

//该线程任务是用来处理指定客户端的请求并给予响应

public class ClientHandler implements Runnable{

    private Socket socket;

    public ClientHandler(Socket socket){

        this.socket=socket;

    }

    public void run(){

         System.out.println("开始处理客户端请求!");

         try{

            HttpRequest request=new HttpRequest(socket);

            HttpResponse response=new HttpResponse(socket);

            String url=request.getUrl();    

            File file=new File("webapps"+url);

            if(file.exist()){

                 System.out.println("找到该文件!");

                 response.setEntity(file);

           }else {

                System.out.println("没有该文件");

           }

            response.flush();

           }catch(Exception e){

           e.printStackTrace();

          }fianlly{

                      try{

                            socket.close();

                        }catch(Exception e){

                            e.printStackTrace();                    

                      }}

          System.out.println("处理请求完毕!");

     }

}

--------------------------------------------------------------------

package com.webserver.http;

import java.io.InputStream;

import java.net.Socket;

//请求对象:HttpRequest的每一个实例用于表示一个客户端发送过来的请求数据

一个请求包含内容:请求行,消息头,消息正文信息

    public  class HttpRequest{

            private Socket socket;

            private InputStream in;

  //定义请求行相关信息

  //请求的方式

   private String method;

   //请求的资源路径

    private String url;

    //请求使用的http协议版本

    private String protocol;

  //通过给定的Socket获取对应客户端发送过来的请求信息并初始化当前HttpRequest对象

    public HttpRequest(Socket socket){

         System.out.println("开始解析请求");

               try{

                       this.socket=socket;

                        this.in=socket.getInputStream();

           //解析请求行分为三步:解析请求行、解析消息头、解析消息正文

                parseRequestLine();

             }catch(Exception e){

               e.prntStackTrace();

             }System.out.println("解析请求完毕!");}

        //解析请求行

                private void parseRequestLine(){

                        System.out.println("开始解析请求行...");

                        try{

                          //读取请求行内容

                           String line=readLine();

                            System.out.println("请求行内容"+line);

                            //这里将来会抛出数组下标越界

                            //拆分字符串

                           String[] data=line.split("\\s");

                           this.method=data[0];

                           this.url=data[1];

                           this.protocol=data[2];

                           System.out.println("method:"+method); 

                           System.out.println("url:"+url);

                           System.out.println("protocol:"+protocol);

                           }catch(Exception e){

                               e.printStackTrace();

                          }

                        System.out.println("解析请求行完毕!.");}

           private String readLine(){

                        StringBuilder builder=new StringBuilder();

                         try{

                            int d=-1;

                            char c1='a',char='a';

                           while((d=in.read())!=-1){

                               c2=(char)d;

                               builder.append(c2);

                               if(c1==13&&c2==10){

                                break;}

                               c1=c2;}

                            }catch(Exception e){

                                  e.printStackTrace();

                             }return builder.toString().trim();

                            }public String getMethod(){

                                  return method; 

                            }public  String getUrl(){

                                  return url;

                           }public String getProtocol(){

                            return protocol;

                           }}

 -------------------------------------------------------------------------

package com.webserver.http;

 import java.io.File;

 import java.io.FileInputStream;

 import java.io.OutputStream;

 import java.net.Socket;

//响应HttpResponse的每一个实例用于表示一个服务daunt发送给客户端的响应内容、一个Http响应包含:状态行、响应行、响      应正文

public  class HttpResponse{

   private Socket socket;

   private OutputStream out;

//响应实体对象

   private File entity;

   public HttpResponse(Socket socket){

       try{

             this.socket=socket;

             this.out=socket.getOutputStream();

          }catch(Exception e){

             e.printStackTrace();

           }}

    //将当前响应对象表示的响应内容发送给客户端

        public void flush(){

        //顺序发送:状态行、响应头、响应正文

       sendStatusLine();

       sendHeaders();

       sendContent();

          }

      //发送状态行

       private void sendStatusLine(){

             try{

                 String line="HTTP/1.1  200 OK";

                 println(line);

               }catch(Exception e){

               e.printStackTrace();

              }}

             //发送响应头

             private void sendHeaders(){

              String line="Content-Type: text/html";

              println(line);

              line="Content-Length:"+entity.length();

              println(line);

               println("");

          }private void sendContent(){

       try{

        FileInputStream fis=new FileInputStream(entity);

        byte[] data=new byte[1024*10];

        int len=-1;

        while((len=fis.read(data))!=-1){

          out.write(data,0,len);

         }catch(Exception e){

         }}

 priate void println(String line){

  try{

    out.write(line.getBytes("ISO8859-1"));

    out.write(13);

    out.write(10);

     }catch(Exception e){

     e.printStackTrace();

    }}

 public File getEntity(){

    return entity;}

 public void setEntity(File entity){

    this.entity=entity;

             

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值