BS通信,代理模式,服务器转发分层代码

来源:互联网 发布:慢镜头软件下载 编辑:程序博客网 时间:2024/05/01 16:43

接上篇BS通信:新增2个类,
一个servlet类:处理相应事务。

package com.dasenlin.testhttp2;/** * 通过servlet来进行封装 * @author Administrator * */public class Servlet {    public void service(Request req,Response rep){        rep.println("<html><head><title>测试</title>");        rep.println("</head><body>");        rep.println("欢迎:").println(req.getParameter("username")).println("回来");        rep.print("</body></html>");    }}

一个dispatcher类,处理接收请求和处理转发的事务

package com.dasenlin.testhttp2;import java.io.IOException;import java.net.Socket;/** * 线程类的转发器 * @author Administrator * */public class Dispatcher implements Runnable{    private Socket client;    private Request req;    private Response rep;    private int code=200;    public Dispatcher(Socket client) {        super();        this.client=client;        try {            req = new Request(client.getInputStream());            rep = new Response(client.getOutputStream());        } catch (IOException e) {            code=500;            return;        }    }    @Override    public void run() {        Servlet servlet =new Servlet();        servlet.service(req, rep);        try {            rep.pushToClient(code);        } catch (IOException e) {            e.printStackTrace();        }        IOUtil.closeAll(client);    }}

修改优化服务器的简洁功能代码

package com.dasenlin.testhttp2;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;/** * 创建服务器并启动,响应 * @author Administrator * */public class Server {    private ServerSocket server;    public static final String CRLF="\r\n";    public static final String BLANK=" ";    public boolean isShutdown =false;    /**     * 启动服务器     */    public static void main(String[] args) {        Server serv = new Server();        serv.start();    }    /**     *      */    public void start(){        start(8888);    }    /**     * 指定端口的启动方法     */    public void start(int port){        try {            server =new ServerSocket(port);            this.recieve();        } catch (IOException e) {            stop();//停止        }    }    /**     *      */    public void stop(){        isShutdown=true;        IOUtil.closeAll(server);    }    /**     * 接收客户端     */    public void recieve(){        try {            while(!isShutdown){                new Thread(new Dispatcher(server.accept())).start();                }        } catch (IOException e) {            stop();//停止        }     }}
0 0