基于Netty4构建HTTP服务----浏览器访问和Netty客户端访问

时间:2022-11-12 09:18:00

基于Netty构建HTTP访问分为两类,使用浏览器访问的和使用Netty客户端访问。在介绍之前,先简单说一下如何使用Netty实现Http服务的。
Netty的Http服务的流程是:
1、Client向Server发送http请求。
2、Server端对http请求进行解析。
3、Server端向client发送http响应。
4、Client对http响应进行解析。
在网上看到一个很好的流程图,很能说明问题:
基于Netty4构建HTTP服务----浏览器访问和Netty客户端访问
其中红色框中的4个类是Netty提供的,它们其实也是一种Handler,其中Encoder继承自ChannelOutboundHandler,Decoder继承自ChannelInboundHandler,它们的作用是:
1、HttpRequestEncoder:对httpRequest进行编码。
2、HttpRequestDecoder:把流数据解析为httpRequest。
3、HttpResponsetEncoder:对httpResponset进行编码。
4、HttpResponseEncoder:把流数据解析为httpResponse。

浏览器访问

HttpServer 类
这个类在浏览器访问和Netty客户端访问时一样的。

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

public class HttpServer {

public void start(int port) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch)
throws Exception {
// server端发送的是httpResponse,所以要使用HttpResponseEncoder进行编码
ch.pipeline().addLast(
new HttpResponseEncoder());
// server端接收到的是httpRequest,所以要使用HttpRequestDecoder进行解码
ch.pipeline().addLast(
new HttpRequestDecoder());
ch.pipeline().addLast(
new HttpServerHandler());
}
}).option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = b.bind(port).sync();

f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}

public static void main(String[] args) throws Exception {
HttpServer server = new HttpServer();
server.start(8000);
}
}

HttpServerHandler 类
直接创建一个response对象,返回值给浏览器。

public class HttpServerHandler extends ChannelInboundHandlerAdapter {
private ByteBufToBytes reader;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
FullHttpResponse response = new DefaultFullHttpResponse(
HTTP_1_1, OK, Unpooled.wrappedBuffer("OK OK OK OK"
.getBytes()));
response.headers().set(CONTENT_TYPE, "text/plain");
response.headers().set(CONTENT_LENGTH,
response.content().readableBytes());
response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
ctx.write(response);
ctx.flush();
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
ctx.close();
}
}

使用浏览器访问,即可获取OK OK OK OK显示在页面上。

Netty客户端访问

服务端的HttpServer 与浏览器访问的一样,HttpServerHandler 写法如下:

import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpUtil;
public class HttpServerHandler extends ChannelInboundHandlerAdapter {
private ByteBufToBytes reader;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
if (msg instanceof HttpRequest) {
HttpRequest request = (HttpRequest) msg;
System.out.println("messageType:"+ request.headers().get("messageType"));
System.out.println("businessType:"+ request.headers().get("businessType"));
if (HttpUtil.isContentLengthSet(request)) {
reader = new ByteBufToBytes(
(int) HttpUtil.getContentLength(request));
}
}
if (msg instanceof HttpContent) {
HttpContent httpContent = (HttpContent) msg;
ByteBuf content = httpContent.content();
reader.reading(content);
content.release();
if (reader.isEnd()) {
String resultStr = new String(reader.readFull());
System.out.println("Client said:" + resultStr);
FullHttpResponse response = new DefaultFullHttpResponse(
HTTP_1_1, OK, Unpooled.wrappedBuffer("I am ok"
.getBytes()));
response.headers().set(CONTENT_TYPE, "text/plain");
response.headers().set(CONTENT_LENGTH,
response.content().readableBytes());
response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
ctx.write(response);
ctx.flush();
}
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
}

还有一个ByteBufToBytes,可以读取NIO的工具类,可以一次性把ByteBuf的数据读取出来,也可以把多次ByteBuf中的数据统一读取出来。

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
public class ByteBufToBytes {
private ByteBuf temp;
private boolean end = true;
public ByteBufToBytes(int length) {
temp = Unpooled.buffer(length);
}
public void reading(ByteBuf datas) {
datas.readBytes(temp, datas.readableBytes());
if (this.temp.writableBytes() != 0) {
end = false;
} else {
end = true;
}
}
public boolean isEnd() {
return end;
}
public byte[] readFull() {
if (end) {
byte[] contentByte = new byte[this.temp.readableBytes()];
this.temp.readBytes(contentByte);
this.temp.release();
return contentByte;
} else {
return null;
}
}
public byte[] read(ByteBuf datas) {
byte[] bytes = new byte[datas.readableBytes()];
datas.readBytes(bytes);
return bytes;
}
}

Netty客户端包括三个类HttpClient,HttpClientHandler和ByteBufToBytes。
HttpClient类


import java.net.URI;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.handler.codec.http.HttpVersion;
public class HttpClient {
public void connect(String host, int port) throws Exception {
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
// 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
ch.pipeline().addLast(new HttpResponseDecoder());
// 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
ch.pipeline().addLast(new HttpRequestEncoder());
ch.pipeline().addLast(new HttpClientHandler());
}
});
ChannelFuture f = b.connect(host, port).sync();
URI uri = new URI("http://127.0.0.1:8000");
String msg = "Are you ok?";
DefaultFullHttpRequest request = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.POST, uri.toASCIIString(),
Unpooled.wrappedBuffer(msg.getBytes()));
// 构建http请求
request.headers().set(HttpHeaderNames.HOST, host);
request.headers().set(HttpHeaderNames.CONNECTION,
HttpHeaderNames.CONNECTION);
request.headers().set(HttpHeaderNames.CONTENT_LENGTH,
request.content().readableBytes());
request.headers().set("messageType", "normal");
request.headers().set("businessType", "testServerState");
// 发送http请求
f.channel().write(request);
f.channel().flush();
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
HttpClient client = new HttpClient();
client.connect("127.0.0.1", 8000);
}
}

HttpClientHandler类

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpUtil;
public class HttpClientHandler extends ChannelInboundHandlerAdapter {
private ByteBufToBytes reader;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
if (msg instanceof HttpResponse) {
HttpResponse response = (HttpResponse) msg;
System.out.println("CONTENT_TYPE:"
+ response.headers().get(HttpHeaderNames.CONTENT_TYPE));
if (HttpUtil.isContentLengthSet(response)) {
reader = new ByteBufToBytes(
(int) HttpUtil.getContentLength(response));
}
}
if (msg instanceof HttpContent) {
HttpContent httpContent = (HttpContent) msg;
ByteBuf content = httpContent.content();
reader.reading(content);
content.release();
if (reader.isEnd()) {
String resultStr = new String(reader.readFull());
System.out.println("Server said:" + resultStr);
ctx.close();
}
}
}
}

最后说几句:

本例中使用Netty4.1.6Final,改写上网上大多例子中的弃用方法。