欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot快速搭建TCP服務(wù)端和客戶端全過程

 更新時間:2025年05月12日 14:45:22   作者:摘星編程  
這篇文章主要介紹了SpringBoot快速搭建TCP服務(wù)端和客戶端全過程,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

由于工作需要,研究了SpringBoot搭建TCP通信的過程,對于工程需要的小伙伴,只是想快速搭建一個可用的服務(wù)。

其他的教程看了許多,感覺講得太復(fù)雜,很容易弄亂,這里我只講效率,展示快速搭建過程。

TCPServer

由于TCP協(xié)議是Netty實現(xiàn)的,所以引入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 #服務(wù)器端口

配置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出現(xiàn)異常", 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 #連接的服務(wù)器端口
  host: 127.0.0.1 #連接的服務(wù)器域名

配置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();
    }
}

這樣就完成了整個搭建過程,重要的就是服務(wù)端的端口和客戶端連接服務(wù)端的URL和接受消息的處理方式,其他的細(xì)節(jié)可以自己慢慢探索。

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Hibernate悲觀鎖和樂觀鎖實例詳解

    Hibernate悲觀鎖和樂觀鎖實例詳解

    這篇文章主要介紹了Hibernate悲觀鎖和樂觀鎖實例詳解,分享了相關(guān)代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下
    2018-02-02
  • mybatis取別名typeAliases標(biāo)簽的位置放錯導(dǎo)致報錯的解決

    mybatis取別名typeAliases標(biāo)簽的位置放錯導(dǎo)致報錯的解決

    這篇文章主要介紹了mybatis取別名typeAliases標(biāo)簽的位置放錯導(dǎo)致報錯的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • java 使用memcached以及spring 配置memcached完整實例代碼

    java 使用memcached以及spring 配置memcached完整實例代碼

    本篇文章主要介紹了java 使用memcached以及spring 配置memcached完整實例代碼,具有一定的參考價值,有興趣的可以了解一下
    2017-07-07
  • 解決spring懶加載以及@PostConstruct結(jié)合的坑

    解決spring懶加載以及@PostConstruct結(jié)合的坑

    這篇文章主要介紹了解決spring懶加載以及@PostConstruct結(jié)合的坑,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Java8?Stream流根據(jù)多個字段去重

    Java8?Stream流根據(jù)多個字段去重

    這篇文章主要介紹了Java8?Stream流根據(jù)多個字段去重,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • 工廠方法在Spring框架中的運用

    工廠方法在Spring框架中的運用

    這篇文章介紹了工廠方法在Spring框架中的運用,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-10-10
  • Java實現(xiàn)求數(shù)組最長子序列算法示例

    Java實現(xiàn)求數(shù)組最長子序列算法示例

    這篇文章主要介紹了Java實現(xiàn)求數(shù)組最長子序列算法,涉及java針對數(shù)組的遞歸遍歷、判斷相關(guān)操作技巧,需要的朋友可以參考下
    2018-07-07
  • Java實現(xiàn)提取QSV文件視頻內(nèi)容

    Java實現(xiàn)提取QSV文件視頻內(nèi)容

    QSV是一種加密的視頻文件格式。是愛奇藝公司研發(fā)的一種視頻文件格式,這篇文章主要為大家介紹了如何利用Java實現(xiàn)提取QSV文件視頻內(nèi)容,感興趣的可以了解一下
    2023-03-03
  • jdbc連接數(shù)據(jù)庫實例詳解

    jdbc連接數(shù)據(jù)庫實例詳解

    在本篇內(nèi)容里小編給大家分享了關(guān)于jdbc如何連接數(shù)據(jù)庫的相關(guān)知識點內(nèi)容,需要的朋友們學(xué)習(xí)下。
    2019-02-02
  • SpringBoot微信消息接口配置詳解

    SpringBoot微信消息接口配置詳解

    這篇文章主要介紹了SpringBoot 微信消息接口配置詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-06-06

最新評論