当前位置:   article > 正文

SpringBoot快速搭建TCP服务端和客户端_springboot tcp server

springboot tcp server

由于工作需要,研究了SpringBoot搭建TCP通信的过程,对于工程需要的小伙伴,只是想快速搭建一个可用的服务.

其他的教程看了许多,感觉讲得太复杂,很容易弄乱,这里我只讲效率,展示快速搭建过程

TCPServer

由于TCP协议是Netty实现的,所以引入Netty的依赖 

  1. <dependency>
  2. <groupId>io.netty</groupId>
  3. <artifactId>netty-all</artifactId>
  4. <version>4.1.25.Final</version>
  5. </dependency>

配置TCPServer

  1. @Component
  2. @Slf4j
  3. @Data
  4. @ConfigurationProperties(prefix = "tcp.server")
  5. public class TCPServer implements CommandLineRunner {
  6. private Integer port;
  7. @Override
  8. public void run(String... args) throws Exception {
  9. EventLoopGroup bossGroup = new NioEventLoopGroup();
  10. EventLoopGroup workerGroup = new NioEventLoopGroup();
  11. try {
  12. ServerBootstrap bootstrap = new ServerBootstrap();
  13. bootstrap.group(bossGroup, workerGroup)
  14. .channel(NioServerSocketChannel.class)
  15. .childHandler(new ChannelInitializer<Channel>() {
  16. @Override
  17. protected void initChannel(Channel channel) throws Exception {
  18. ChannelPipeline pipeline = channel.pipeline();
  19. pipeline.addLast(new StringEncoder());
  20. pipeline.addLast(new StringDecoder());
  21. pipeline.addLast(new TCPServerHandler());
  22. }
  23. })
  24. .option(ChannelOption.SO_BACKLOG, 128)
  25. .childOption(ChannelOption.SO_KEEPALIVE, true);
  26. ChannelFuture future = bootstrap.bind(port).sync();
  27. log.info("TCP server started and listening on port " + port);
  28. future.channel().closeFuture().sync();
  29. } finally {
  30. workerGroup.shutdownGracefully();
  31. bossGroup.shutdownGracefully();
  32. }
  33. }
  34. }

application.yml配置文件

  1. tcp:
  2. server:
  3. port: 8888 #服务器端口

配置TCPServerHandler

  1. @Slf4j
  2. @Component
  3. public class TCPServerHandler extends SimpleChannelInboundHandler<String> {
  4. @Override
  5. protected void channelRead0(ChannelHandlerContext ctx, String msg) {
  6. log.info("收到客户端消息:/n"+ msg);
  7. Object parse = JSONUtils.parse(msg);
  8. System.out.println("parse = " + parse);
  9. }
  10. @Override
  11. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
  12. log.error("TCPServer出现异常", cause);
  13. ctx.close();
  14. }
  15. }

TCPClient

客户端的配置大同小异

Netty依赖

  1. <dependency>
  2. <groupId>io.netty</groupId>
  3. <artifactId>netty-all</artifactId>
  4. <version>4.1.25.Final</version>
  5. </dependency>

配置TCPClient

  1. @Component
  2. @Slf4j
  3. @Data
  4. @ConfigurationProperties(prefix = "tcp.client")
  5. public class TCPClient implements CommandLineRunner {
  6. private String host ;
  7. private Integer port;
  8. @Override
  9. public void run(String... args) throws Exception {
  10. EventLoopGroup group = new NioEventLoopGroup();
  11. try {
  12. Bootstrap bootstrap = new Bootstrap()
  13. .group(group)
  14. .channel(NioSocketChannel.class)
  15. .handler(new ChannelInitializer<SocketChannel>() {
  16. @Override
  17. protected void initChannel(SocketChannel ch) throws Exception {
  18. ChannelPipeline pipeline = ch.pipeline();
  19. pipeline.addLast(new StringEncoder());
  20. pipeline.addLast(new StringDecoder());
  21. pipeline.addLast(new TCPClientHandler());
  22. }
  23. });
  24. ChannelFuture future = bootstrap.connect(host, port).sync();
  25. log.info("TCPClient Start , Connect host:"+host+":"+port);
  26. future.channel().closeFuture().sync();
  27. } catch (Exception e) {
  28. log.error("TCPClient Error", e);
  29. } finally {
  30. group.shutdownGracefully();
  31. }
  32. }
  33. }

application.yml配置文件

  1. tcp:
  2. client:
  3. port: 8080 #连接的服务器端口
  4. host: 127.0.0.1 #连接的服务器域名

配置TCPServerHandler

  1. @Slf4j
  2. @Component
  3. public class TCPClientHandler extends SimpleChannelInboundHandler<String> {
  4. @Override
  5. protected void channelRead0(ChannelHandlerContext ctx, String msg) {
  6. log.info("Receive TCPServer Message:\n"+ msg);
  7. }
  8. @Override
  9. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
  10. log.error("TCPClient Error", cause);
  11. ctx.close();
  12. }
  13. }

这样就完成了整个搭建过程,重要的就是服务端的端口和客户端连接服务端的URL和接受消息的处理方式,其他的细节可以自己慢慢探索.

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

闽ICP备14008679号