/**
* 发生异常
*/
@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 ServerPipelineFactory());
// 创建服务器端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);