注:黑色部分代码与netty-action-01一致,请看netty-01部分
1、netty - channel 生命周期的描述
package com.renxiaobo.wechat.demo01;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
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.util.CharsetUtil;
/**
-
Author:rxb
-
Date:2020-06-10 20:44
-
Description:客户端发送一个请求,服务端返回hello netty
*/
public class HelloServer {public static void main(String[] args) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(“HttpServerCodec”, new HttpServerCodec());//netty自己提供的 助手类,当请求到服务端,需要-解码,响应到客户-做编码
pipeline.addLast(new ChildHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(8081).sync();
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}}
}
/***************************************************************
** 这是一个漂亮的分隔符
***************************************************************/
class ChildHandler extends SimpleChannelInboundHandler {
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
Channel channel = ctx.channel();
if(msg instanceof HttpRequest && !((HttpRequest) msg).uri().contains