Netty-客户端及服务端代码模式

喜欢ヅ旅行 2022-09-10 06:28 332阅读 0赞

一、服务端代码模板

  1. public class NettyServer {
  2. public static void main(String[] args) throws InterruptedException {
  3. //server启动器
  4. ServerBootstrap serverBootstrap = new ServerBootstrap();
  5. //boss线程组,监听端口链接
  6. NioEventLoopGroup boss = new NioEventLoopGroup(1);
  7. //worker线程组,监听数据读写
  8. NioEventLoopGroup worker = new NioEventLoopGroup();
  9. try {
  10. serverBootstrap
  11. //1.指定线程组
  12. .group(boss, worker)
  13. //2.指定线程模型
  14. .channel(NioServerSocketChannel.class)
  15. //3.初始化pipeline
  16. .childHandler(new ChannelInitializer<NioSocketChannel>() {
  17. protected void initChannel(NioSocketChannel ch) {
  18. ch.pipeline().addLast(new StringDecoder());
  19. ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
  20. @Override
  21. protected void channelRead0(ChannelHandlerContext ctx, String msg) {
  22. System.out.println(msg);
  23. }
  24. });
  25. }
  26. });
  27. //5.绑定端口并阻塞至完成
  28. ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
  29. //6.阻塞当前线程至ServerSocketChannel关闭(根据情况判断是否阻塞当前线程,也可以添加监听器进行关闭)
  30. channelFuture.channel().closeFuture().sync();
  31. }finally {
  32. //7.优雅关闭
  33. boss.shutdownGracefully();
  34. worker.shutdownGracefully();
  35. }
  36. }
  37. }

二、客户端代码模板

  1. public class NettyClient {
  2. public static void main(String[] args) throws InterruptedException {
  3. //启动器
  4. Bootstrap bootstrap = new Bootstrap();
  5. //线程组,客户端不需要监听端口,只需要一个线程组
  6. NioEventLoopGroup group = new NioEventLoopGroup();
  7. try {
  8. bootstrap
  9. //1.指定线程组
  10. .group(group)
  11. //2.指定线程模型
  12. .channel(NioSocketChannel.class)
  13. //3.初始化pipeline
  14. .handler(new ChannelInitializer<SocketChannel>() {
  15. @Override
  16. protected void initChannel(SocketChannel ch) {
  17. ch.pipeline().addLast(new StringEncoder());
  18. }
  19. });
  20. //4.链接服务端
  21. ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8888).sync();
  22. //5.获取channel(一般都单独保存,用于通信)
  23. Channel channel = channelFuture.channel();
  24. //6.阻塞当前线程至SocketChannel关闭(根据情况判断是否阻塞当前线程,也可以添加监听器进行关闭,客户端一般都不需要阻塞)
  25. channel.closeFuture().sync();
  26. } finally {
  27. //7.优雅关闭
  28. group.shutdownGracefully();
  29. }
  30. }
  31. }

发表评论

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

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

相关阅读

    相关 Netty实现客户服务通信

    实现一个客户端与服务端通信的程序,可以使用socket网络编程来实现,而Netty作为一个封装了JDK的NIO通讯的异步事件驱动的网络应用框架,也同样可以实现。 1.创建M