Netty 实现HTTP通信
1. 服务端实现
public class MyHttpServer {
private ServerBootstrap serverBootstrap;
private Integer port;
public MyHttpServer(Integer port) {
this.port = port;
serverBootstrap = new ServerBootstrap();
}
public MyHttpServer() {
this(8888);
}
public void start() {
NioEventLoopGroup boss = new NioEventLoopGroup(1);
NioEventLoopGroup work = new NioEventLoopGroup();
try {
serverBootstrap.group(boss, work)
.channel(NioServerSocketChannel.class)
.localAddress(port)
.childHandler(new MyHttpInitializer());
ChannelFuture bindFuture = serverBootstrap.bind().sync();
ChannelFuture sync = bindFuture.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. Handler实现
- 此处使用了SimpleChannelInboundHandler, 这里的HttpObject实际上代表着浏览器的请求
public class MyHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
protected void channelRead0(
ChannelHandlerContext ctx,
HttpObject httpObject) throws Exception {
if (httpObject instanceof HttpRequest) {
DefaultHttpRequest request = (DefaultHttpRequest) httpObject;
System.out.println(request.uri());
ByteBuf byteBuf = Unpooled.copiedBuffer("hello world netty http", CharsetUtil.UTF_8);
HttpResponse response = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
HttpResponseStatus.OK,
byteBuf);
response.headers()
.set(HttpHeaderNames.CONTENT_TYPE, "text/plain")
.set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());
ctx.writeAndFlush(response);
}
}
}
3. 添加通道处理器
- HttpServerCodec是Netty默认提供的解析HTTP请求的编解码器
public class MyHttpInitializer extends ChannelInitializer {
protected void initChannel(Channel channel) throws Exception {
channel.pipeline().addLast(new HttpServerCodec());
channel.pipeline().addLast(new MyHttpServerHandler());
}
}
4. 客户端
public class Entry {
public static void main(String[] args) {
MyHttpServer myHttpServer = new MyHttpServer();
myHttpServer.start();
}
}