设为首页 加入收藏

TOP

使用Netty3或Netty4发布Http协议服务(二)
2018-01-17 13:05:18 】 浏览:445
Tags:使用 Netty3 Netty4 发布 Http 协议 服务
的长度
        response.setHeader("Content-Length", response.getContent().writerIndex());
        Channel ch = e.getChannel();


        // 响应给客户端
        ChannelFuture f = ch.write(response);


        // 数据发送完毕,则关闭连接通道.
        f.addListener(new ChannelFutureListener()
        {
            public void operationComplete(ChannelFuture future) throws Exception
            {
                future.getChannel().close();
            }
        });
    }


    /**
    * 发生异常
    */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
    {
        LOGGER.error("exceptionCaught(): ", e.getCause());
        e.getCause().printStackTrace();
    }


}


第二步:创建Http管道类工厂用来联结Http业务处理服务类,代码如下


package com.alanlee.http;


import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
import org.jboss.netty.handler.codec.http.HttpResponseEncoder;


/**
 * HTTP管道类工厂.
 *
 * @author AlanLee
 * @version 2018/01/11
 *
 */
public class ServerPipelineFactory implements ChannelPipelineFactory
{


    /**
    * 获取管道.
    *
    * @return ChannelPipeline 管道
    */
    public ChannelPipeline getPipeline()
    {
        ChannelPipeline pipeline = Channels.pipeline();
        System.out.println("initChannel pipeline");
        // 解码
        pipeline.addLast("decoder", new HttpRequestDecoder(1024, 1024, 1000 * 1024));
        // 编码
        pipeline.addLast("encoder", new HttpResponseEncoder());
        // 请求的业务类
        pipeline.addLast("handler", new HttpServerHandler());
        return pipeline;
    }


}


最后,让我们利用Netty3来发布Http协议服务接口,代码如下


package com.alanlee.http;


import java.net.InetSocketAddress;
import java.util.concurrent.Executors;


import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;


/**
 * http服务启动类
 *
 * @author AlanLee
 * @version 2018/01/11
 *
 */
public class HttpServer
{


    public static void main(String[] args)
    {
        ChannelFactory factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
                Executors.newCachedThreadPool());
        // 初始化channel的辅助类
        ServerBootstrap bootstrap = new ServerBootstrap(factory);
        bootstrap.setPipelineFactory(new ServerPipe

首页 上一页 1 2 3 4 5 下一页 尾页 2/5/5
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇使用Netty3或Netty4发布Http协议.. 下一篇Spring Web项目spring配置文件随..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目