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