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

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

码农世界 2024-05-22 后端 61 次浏览 0个评论

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

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

TCPServer

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


  io.netty
  netty-all
  4.1.25.Final

配置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() {
                @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 {
    @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依赖


  io.netty
  netty-all
  4.1.25.Final

配置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() {
                        @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 {
    @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和接受消息的处理方式,其他的细节可以自己慢慢探索.

转载请注明来自码农世界,本文标题:《SpringBoot快速搭建TCP服务端和客户端》

百度分享代码,如果开启HTTPS请参考李洋个人博客
每一天,每一秒,你所做的决定都会改变你的人生!

发表评论

快捷回复:

评论列表 (暂无评论,61人围观)参与讨论

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

Top