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

8 篇文章 0 订阅

接上篇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();//停止
        } 
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值