import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
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.*;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.AsciiString;
import io.netty.util.CharsetUtil;
import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpHeaderValues.CLOSE;
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
public class NettyTest {
public static void main(String[] args) throws InterruptedException {
int port = 80;
ServerBootstrap http = new ServerBootstrap();
NioEventLoopGroup bossGroup = new NioEventLoopGroup(2);
NioEventLoopGroup workGroup = new NioEventLoopGroup(2);
http.group(bossGroup, workGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpRequestDecoder());//请求解码器
pipeline.addLast(new HttpResponseEncoder());//响应编码器
pipeline.addLast(new HttpObjectAggregator(65535));
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new FormatRequestParamHandler());//入口逻辑处理
pipeline.addLast(new BusinessHandler());//下一个入口逻辑处理
}
});
Channel ch = http.bind(port).sync().channel();
ch.closeFuture().sync(); // 等待服务端监听到端口关闭
workGroup.shutdownGracefully();//回收资源
bossGroup.shutdownGracefully();
}
static class FormatRequestParamHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
boolean keepAlive = HttpUtil.isKeepAlive(request);//连接类型
if (!request.decoderResult().isSuccess()) return;//判断解码是否成功
if (request.uri().equals("/favicon.ico")) {//过滤图标请求
FullHttpResponse response = getResponse("图标");
sendAndCleanupConnection(ctx, response, keepAlive);
return;
}
ctx.fireChannelRead("将当前处理的参数放下发");//往下发
}
}
static class BusinessHandler extends SimpleChannelInboundHandler<String> {
/**
* 逻辑处理
*
* @param ctx
* @param msg 上一个串口传入的参数
* @throws Exception
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
FullHttpResponse response = getResponse(msg);
sendAndCleanupConnection(ctx, response, true);//在上一个串口需要把链接类型带过来 这里用
}
}
private static FullHttpResponse getResponse(String respMsg) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK, Unpooled.copiedBuffer(respMsg, CharsetUtil.UTF_8));
response.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8");//设置响应头
return response;
}
/**
* 发送响应
*/
public static void sendAndCleanupConnection(ChannelHandlerContext ctx, FullHttpResponse response, boolean keepAliveStatus) {
Channel channel = ctx.channel();
AsciiString keepAlive = keepAliveStatus ? KEEP_ALIVE : CLOSE;
response.headers().set(CONNECTION, keepAlive);// 如果不是长连接,设置 connection:close 头部
HttpUtil.setContentLength(response, response.content().readableBytes());
ChannelFuture writePromise = channel.writeAndFlush(response); //发送内容
if (!HttpUtil.isKeepAlive(response))
writePromise.addListener(ChannelFutureListener.CLOSE); // 如果不是长连接,发送完成之后,关闭连接
}
}
Java Netty Demo
于 2024-08-13 18:05:52 首次发布