设为首页 加入收藏

TOP

使用Netty3或Netty4发布Http协议服务(五)
2018-01-17 13:05:18 】 浏览:448
Tags:使用 Netty3 Netty4 发布 Http 协议 服务
id exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
    {
        System.out.println("exceptionCaught");
        if (null != cause)
            cause.printStackTrace();
        if (null != ctx)
            ctx.close();
    }


}


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


package com.alanlee.netty2;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;


/**
 * 搭建HttpServer
 *
 * @author Alanlee
 * @version 2018/01/11
 *
 */
public class HttpServer
{


    private final int port;


    public HttpServer(int port)
    {
        this.port = port;
    }


    public static void main(String[] args) throws InterruptedException
    {
        new HttpServer(8081).start();
        System.out.println("Start http server success!");
    }


    public void start() throws InterruptedException
    {
        // 初始化channel的辅助类
        ServerBootstrap b = new ServerBootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        b.group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>()
        {
            /**
            * 初始化channel
            */
            @Override
            protected void initChannel(SocketChannel ch) throws Exception
            {
                System.out.println("initChannel ch:" + ch);
                // 获取管道
                ch.pipeline().addLast("decoder", new HttpRequestDecoder())  // 解码
                        .addLast("encoder", new HttpResponseEncoder())      // 编码
                        /* aggregator,消息聚合器(重要)。
                        Netty4中为什么能有FullHttpRequest这个东西,
                        就是因为有他,HttpObjectAggregator,如果没有他,
                        就不会有那个消息是FullHttpRequest的那段Channel,
                        同样也不会有FullHttpResponse,HttpObjectAggregator(512 * 1024)的参数含义是消息合并的数据大小,
  &n

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

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目