SpringBoot快速搭建TCP服务端和客户端全过程

 更新时间:2025年05月12日 14:45:22   作者:摘星编程  
这篇文章主要介绍了SpringBoot快速搭建TCP服务端和客户端全过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

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

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

TCPServer

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

<dependency>
  <groupId>io.netty</groupId>
  <artifactId>netty-all</artifactId>
  <version>4.1.25.Final</version>
</dependency>

配置TCPServer

@Component
@Slf4j
@Data
@ConfigurationProperties(prefix = "tcp.server")
public class TCPServer implements CommandLineRunner {
    private Integer port;

    @Override
    public void run(String... args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    pipeline.addLast(new StringEncoder());
                    pipeline.addLast(new StringDecoder());
                    pipeline.addLast(new TCPServerHandler());
                }
            })
            .option(ChannelOption.SO_BACKLOG, 128)
            .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture future = bootstrap.bind(port).sync();
            log.info("TCP server started and listening on port " + port);

            future.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}

application.yml配置文件

tcp:
 server:
  port: 8888 #服务器端口

配置TCPServerHandler

@Slf4j
@Component
public class TCPServerHandler extends SimpleChannelInboundHandler<String> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        log.info("收到客户端消息:/n"+ msg);
        Object parse = JSONUtils.parse(msg);
        System.out.println("parse = " + parse);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("TCPServer出现异常", cause);
        ctx.close();
    }
}

TCPClient

客户端的配置大同小异

Netty依赖

<dependency>
  <groupId>io.netty</groupId>
  <artifactId>netty-all</artifactId>
  <version>4.1.25.Final</version>
</dependency>

配置TCPClient

@Component
@Slf4j
@Data
@ConfigurationProperties(prefix = "tcp.client")
public class TCPClient implements CommandLineRunner {
    private String host ;
    private Integer port;
    @Override
    public void run(String... args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new TCPClientHandler());
                        }
                    });
            ChannelFuture future = bootstrap.connect(host, port).sync();
            log.info("TCPClient Start , Connect host:"+host+":"+port);
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("TCPClient Error", e);
        } finally {
            group.shutdownGracefully();
        }
    }
}

application.yml配置文件

tcp:
 client:
  port: 8080 #连接的服务器端口
  host: 127.0.0.1 #连接的服务器域名

配置TCPServerHandler

@Slf4j
@Component
public class TCPClientHandler extends SimpleChannelInboundHandler<String> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        log.info("Receive TCPServer Message:\n"+ msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("TCPClient Error", cause);
        ctx.close();
    }
}

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

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • MyBatis配置不同级别的日志输出

    MyBatis配置不同级别的日志输出

    MyBatis提供多种日志框架集成,如SLF4J、Log4j2、Logback等,通过配置日志框架和调整日志级别,可以实现详细的SQL日志记录,本文就来介绍一下,感兴趣的可以了解一下
    2024-12-12
  • jxls2.4.5如何动态导出excel表头与数据

    jxls2.4.5如何动态导出excel表头与数据

    这篇文章主要介绍了jxls2.4.5如何动态导出excel表头与数据问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-08-08
  • MAC下如何设置JDK环境变量

    MAC下如何设置JDK环境变量

    这篇文章主要介绍了MAC下如何设置JDK环境变量问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • java的http请求工具对比分析

    java的http请求工具对比分析

    本文对比了Java中五种流行的HTTP客户端库:HttpURLConnection、ApacheHttpClient、OkHttp、Feign和SpringRestTemplate,涵盖了它们的特性、优势、劣势以及适用场景,感兴趣的朋友一起看看吧
    2025-03-03
  • 手把手教你搞懂冒泡排序和选择排序

    手把手教你搞懂冒泡排序和选择排序

    这篇文章主要介绍了java数组算法例题代码详解(冒泡排序,选择排序),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-07-07
  • springboot集成mqtt的实践开发

    springboot集成mqtt的实践开发

    本篇文章主要介绍了springboot集成mqtt的实践开发,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-08-08
  • springcloud下hibernate本地化方言配置方式

    springcloud下hibernate本地化方言配置方式

    这篇文章主要介绍了springcloud下hibernate本地化方言配置方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-09-09
  • Mybatis错误引起的程序启动卡死问题及解决

    Mybatis错误引起的程序启动卡死问题及解决

    这篇文章主要介绍了Mybatis错误引起的程序启动卡死问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-02-02
  • Java编程中ArrayList源码分析

    Java编程中ArrayList源码分析

    这篇文章主要介绍了Java编程中ArrayList源码分析,具有一定借鉴价值,需要的朋友可以参考下。
    2017-12-12
  • Java学习字符串之方法返回、跳出嵌套循环及正则表达式

    Java学习字符串之方法返回、跳出嵌套循环及正则表达式

    这篇文章主要介绍了Java学习字符串之方法返回、跳出嵌套循环及正则表达式的相关资料,包括字符串的基本操作(如长度、截取、替换等)以及正则表达式的匹配和替换操作,需要的朋友可以参考下
    2026-03-03

最新评论