的长度
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