当前位置:   article > 正文

netty的TCP服务端和客户端实现

netty的TCP服务端和客户端实现

第一步:引入依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>io.netty</groupId>
  4. <artifactId>netty-all</artifactId>
  5. <version>4.1.90.Final</version>
  6. </dependency>
  7. </dependencies>

第二步:实现TCP服务端

  1. package org.cyl.tcputils;
  2. import io.netty.bootstrap.ServerBootstrap;
  3. import io.netty.channel.ChannelFuture;
  4. import io.netty.channel.ChannelInitializer;
  5. import io.netty.channel.ChannelPipeline;
  6. import io.netty.channel.nio.NioEventLoopGroup;
  7. import io.netty.channel.socket.SocketChannel;
  8. import io.netty.channel.socket.nio.NioServerSocketChannel;
  9. import io.netty.handler.logging.LogLevel;
  10. import io.netty.handler.logging.LoggingHandler;
  11. import org.cyl.tcputils.handle.MyInboundHandler;
  12. public class TcpServer {
  13. public static void main(String[] args) throws InterruptedException {
  14. NioEventLoopGroup bossGroup = new NioEventLoopGroup();
  15. NioEventLoopGroup workerGroup = new NioEventLoopGroup();
  16. try {
  17. ServerBootstrap serverBootstrap = new ServerBootstrap();
  18. serverBootstrap.group(bossGroup, workerGroup)
  19. .channel(NioServerSocketChannel.class)
  20. .handler(new LoggingHandler(LogLevel.INFO))
  21. .childHandler(new ChannelInitializer<SocketChannel>() {
  22. @Override
  23. protected void initChannel(SocketChannel ch) throws Exception {
  24. ChannelPipeline pipeline = ch.pipeline();
  25. // 添加自定义处理器
  26. }
  27. });
  28. ChannelFuture channelFuture = serverBootstrap.bind(8080).sync();
  29. channelFuture.channel().closeFuture().sync();
  30. } finally {
  31. bossGroup.shutdownGracefully();
  32. workerGroup.shutdownGracefully();
  33. }
  34. }
  35. }

第三步:实现TCP客户端

  1. package org.cyl.tcputils;
  2. import io.netty.bootstrap.Bootstrap;
  3. import io.netty.channel.*;
  4. import io.netty.channel.nio.NioEventLoopGroup;
  5. import io.netty.channel.socket.SocketChannel;
  6. import io.netty.channel.socket.nio.NioSocketChannel;
  7. public class TcpClient {
  8. public static void main(String[] args) throws InterruptedException {
  9. EventLoopGroup group = new NioEventLoopGroup();
  10. try {
  11. Bootstrap bootstrap = new Bootstrap();
  12. bootstrap.group(group)
  13. .channel(NioSocketChannel.class)
  14. .option(ChannelOption.TCP_NODELAY, true)
  15. .handler(new ChannelInitializer<SocketChannel>() {
  16. @Override
  17. protected void initChannel(SocketChannel ch) throws Exception {
  18. ChannelPipeline pipeline = ch.pipeline();
  19. // 添加自定义处理器
  20. }
  21. });
  22. ChannelFuture channelFuture = bootstrap.connect("localhost", 8080).sync();
  23. channelFuture.channel().closeFuture().sync();
  24. } finally {
  25. group.shutdownGracefully();
  26. }
  27. }
  28. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/143996
推荐阅读
相关标签
  

闽ICP备14008679号