初学netty 原理后面再弄 ,首先还得熟悉整体流程以及代码的熟练度
1.程序入口
public class main {
public static void main(String[] args) throws Exception {
//boss线程
EventLoopGroup boss = new NioEventLoopGroup();
//worker线程
EventLoopGroup worker = new NioEventLoopGroup();
try {
//新建一个可以快速启动服务对象
ServerBootstrap server = new ServerBootstrap();
//指定boss worker线程
server.group(boss, worker).channel(NioServerSocketChannel.class)
.childHandler(new MyServerInitializer());
//绑定端口号
ChannelFuture future = server.bind(8080).sync();
future.channel().closeFuture().sync();
} finally {
//优雅的关闭两类线程
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
}
2.构建自己的handler初始化
public class MyServerInitializer extends ChannelInitializer {
@Override
protected void initChannel(Channel channel) throws Exception {
//得到管道
ChannelPipeline pipeline = channel.pipeline();
//末尾添加http编码器和解码器(HttpServerCodec是同时拥有解码编码的功能)
pipeline.addLast(new HttpServerCodec());
//添加自己的handler
pipeline.addLast(new MyServerHandler());
}
}
3.创建自己的handler
class MyServerHandler extends SimpleChannelInboundHandler<HttpRequest> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest request) throws Exception {
ByteBuf content = Unpooled.copiedBuffer("测试", CharsetUtil.UTF_8);
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain;charset=UTF-8");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
ctx.writeAndFlush(response);
}
}
4.测试
在浏览器中直接敲http://localhost:8080
得到结果