Java Netty 学习笔记(二)使用Netty编程

电玩女神 2022-06-15 02:53 276阅读 0赞

熟悉了使用java nio编程的套路,实际上就跟底层socket的没啥区别。
下面学习如何使用Netty编写简单的Time Server。
代码:https://github.com/NearXdu/NettyLearn

  1. public class TimeServer {
  2. public void bind(int port) throws Exception{
  3. //配置服务端的NIO线程组
  4. //
  5. EventLoopGroup bossGroup = new NioEventLoopGroup();
  6. EventLoopGroup workerGroup = new NioEventLoopGroup();
  7. try{
  8. ServerBootstrap b = new ServerBootstrap();
  9. b.group(bossGroup,workerGroup)
  10. .channel(NioServerSocketChannel.class)
  11. .option(ChannelOption.SO_BACKLOG,1024)
  12. .childHandler(new ChildChannelHandler());
  13. //绑定端口,同步等待成功
  14. ChannelFuture f = b.bind(port).sync();
  15. //等待服务端监听端口关闭
  16. f.channel().closeFuture().sync();
  17. }finally {
  18. //释放线程池资源
  19. bossGroup.shutdownGracefully();
  20. workerGroup.shutdownGracefully();
  21. }
  22. }
  23. private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
  24. @Override
  25. protected void initChannel(SocketChannel ch) throws Exception {
  26. ch.pipeline().addLast(new TimeServerHandler());
  27. }
  28. }
  29. public static void main(String[] args) throws Exception{
  30. int port =1025;
  31. if(args!=null && args.length>0){
  32. try{
  33. port =Integer.valueOf(args[0]);
  34. }catch (NumberFormatException e){
  35. }
  36. }
  37. new TimeServer().bind(port);
  38. }
  39. }

1.NioEventLoopGroup:Reactor线程组,用于处理网络事件。
2.ServerBootstrap:Netty用于启动NIO服务端的辅助启动类。
3.ServerBootstrapgroup方法设置监听套接字NioServerSocketChannel
设置BACKLOG,设置IO事件的处理类ChildChannelHandler
4.ServerBootstrapbind方法绑定监听端口

在Handler类中,有些区别就是netty4和netty5的API会有些出入,在书中继承ChannelHandlerAdapter,我用的是Netty4,因此需要稍微改写:

  1. public class TimeServerHandler extends ChannelInboundHandlerAdapter {
  2. @Override
  3. public void channelRead(ChannelHandlerContext ctx, Object msg)
  4. throws Exception {
  5. ByteBuf buf = (ByteBuf) msg;//read buff
  6. byte[] req = new byte[buf.readableBytes()];//通过readble获取到大小
  7. buf.readBytes(req);//readByte将数据塞入req中
  8. //业务
  9. String body = new String(req, "UTF-8");
  10. System.out.println("The time server receive order : " + body);
  11. String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body.trim()) ? new java.util.Date(
  12. System.currentTimeMillis()).toString() : "BAD ORDER";
  13. //构造响应
  14. ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
  15. //发送
  16. ctx.write(resp);
  17. }
  18. }

这个方法就有点类似muduo中onMessage,或者libevent中onRead回调了,数据通过参数传递,并使用封装的缓存接收,最后构造业务响应。

参考:
1) netty权威指南
2) http://stackoverflow.com/questions/24844042/extends-channelhandleradapter-but-does-not-override-or-implement-a-method-from

发表评论

表情:
评论列表 (有 0 条评论,276人围观)

还没有评论,来说两句吧...

相关阅读

    相关 netty学习笔记

    Netty与原生Nio的区别 原生的nio,只简单封闭了ByteBuffer以及Channel,也就是网络IO操作以及对这些字节的缓存,字节的编码与解码、粘包与拆包

    相关 netty学习笔记

    Netty架构,特性、模块组件、线程模型(Boss线程、worker线程)以及源码、 netty架构图: ![70][] netty架构五部分: Extensible