设为首页 加入收藏

TOP

使用Netty3或Netty4发布Http协议服务(四)
2018-01-17 13:05:18 】 浏览:447
Tags:使用 Netty3 Netty4 发布 Http 协议 服务
lineFactory());
        // 创建服务器端channel的辅助类,接收connection请求
        bootstrap.bind(new InetSocketAddress(8080));
        System.out.println("Start http server success!");
    }
}


Netty4实现Http协议服务接口步骤:


第一步:创建Http业务处理服务类,代码如下


package com.alanlee.netty2;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.AsciiString;


/**
 * HttpServer业务处理
 *
 * @author AlanLee
 * @version 2018/01/11
 *
 */
public class HttpHandler extends SimpleChannelInboundHandler<FullHttpRequest>
{


    private AsciiString contentType = HttpHeaderValues.TEXT_PLAIN;


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception
    {
        String method = msg.method().name(); // 请求方式
        String url = msg.uri().toLowerCase(); // 请求路径
        System.out.println(method);
        System.out.println(url);


        // 接收请求内容并打印
        ByteBuf byteBuf = msg.content();
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        String requestStr = new String(bytes, "UTF-8");
        System.out.println(requestStr);


        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                Unpooled.wrappedBuffer("你才是猪!".getBytes()));


        HttpHeaders heads = response.headers();
        // 返???内容的MIME类型
        heads.add(HttpHeaderNames.CONTENT_TYPE, contentType + "; charset=UTF-8");
        // 响应体的长度
        heads.add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        // 表示是否需要持久连接
        heads.add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);


        // 响应给客户端
        ctx.write(response);
    }


    /**
    * 数据发送完毕,则关闭连接通道.
    */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception
    {
        System.out.println("channelReadComplete");
        super.channelReadComplete(ctx);
        ctx.flush();
    }


    /**
    * 发生异常
    */
    @Override
    public vo

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

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目