SpringBoot基于Netty实现对接硬件,接受硬件报文

主要项目框架采用的事若依的框架,就不做多介绍

下面主要贴代码和部分注释

在pom.xml文件中引入netty包

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

2、编写NettyServer类

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

/**
 * @Author DCXPC
 * @Description //TODO 采用netty 监听服务器端口,并处理后面逻辑
 * @Date 2023/9/15 9:57
 **/
@Component
public class NettyServer {

    private final int port = 9007;

    public void start() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    // 指定Channel
                    .channel(NioServerSocketChannel.class)
                    //使用自定义处理类
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 添加自定义的ChannelHandler
                            pipeline.addLast(new MyChannelHandler());
                        }
                    })
                    //服务端可连接队列数,对应TCP/IP协议listen函数中backlog参数
                    .option(ChannelOption.SO_BACKLOG, 128)
                    //保持长连接,2小时无数据激活心跳机制
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            // 绑定端口,开始接收进来的连接
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}

3、编写自定义处理类MyChannelHandler

package com.ruoyi.common.netty;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author DCXPC
 * @ClassName MyChannelHandler
 * @description: TODO 自定义的数据处理方法,用于处理收到的数据
 * @date 2023年09月14日
 */
public class MyChannelHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 处理接收到的数据
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("----------------------------------------------------------------------------------------------------");
        System.out.println("Received time: " +sdf.format(new Date()));
        /**数据转换**/
        // 获取字节数组
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.getBytes(byteBuf.readerIndex(), bytes);
        // 将字节数组转换为十六进制字符串
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hexString.append('0'); // 如果得到的十六进制只有一位,则在前面补零
            }
            hexString.append(hex);
        }
        String hexStringResult = hexString.toString(); // 转换后的十六进制字符串
        System.out.println("Received data:"+hexStringResult);
        dealData(hexStringResult);

        /**接收到的数据是水文规约,需要翻译成有用的数据*/
//        dealData(
//                "7e7e" +//4
//                "01" +//6
//                "0034120201" +//16
//                "1234" +//20
//                "32" +//22
//                "003b" +//26
//                "02" +//28
//                "0102" +//32
//                "230914203800" +//44
//                "f1f1" +//48
//                "0034120201" +//58
//                "49" +//60
//                "f0f0" +//64
//                "2309142038" +//74
//                "3c23" +//水位引导    78
//                "00002321" +//水位2.321    86
//                "682a" +//表1瞬时流量引导     90
//                "0000004644" +//表1瞬时流量46.44    100
//                "6033" +//表1累积流量引导      104
//                "000012369332" +//表1累积流量12369.332     116
//                "692a" +//表2瞬时流量引导  120
//                "0000008723" +//表2瞬时流量87.23     130
//                "6133" +//表2累积流量引导        134
//                "000023223654" +//表2累积流量23223.654     146
//                "03ecaf");
        byteBuf.release();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 处理异常
        cause.printStackTrace();
        ctx.close();
    }

    //处理数据
    public void dealData(String hexMsg){

        String date = hexMsg.substring(32,44);
        System.out.println("发报时间:"+date);

        String waterleve = hexMsg.substring(78,86);
        System.out.println("水位高度:"+addpoint(waterleve,hexMsg.substring(77,78)));;

        String ssll1 = hexMsg.substring(90,100);
        System.out.println("表1瞬时流量:"+addpoint(ssll1,"2"));;

        String ljll1 = hexMsg.substring(104,116);
        System.out.println("表1累积流量:"+addpoint(ljll1,"3"));;

        String ssll2 = hexMsg.substring(120,130);
        System.out.println("表2瞬时流量:"+addpoint(ssll2,"2"));;

        String ljll2 = hexMsg.substring(134,146);
        System.out.println("表2累积流量:"+addpoint(ljll2,"3"));;


    }

    //小数点添加
    public float addpoint(String numStr,String locationStr){
        int locationNum = Integer.valueOf(locationStr);
        StringBuilder sb = new StringBuilder(numStr);
        sb.insert(numStr.length()-locationNum,".");
        float num = Float.valueOf(sb.toString());
        return num;
    }




}

4、在启动类上加上该启动配置

import com.ruoyi.common.netty.NettyServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

/**
 * 启动程序
 *
 * @author ruoyi
 */
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class RuoYiApplication implements CommandLineRunner {

    @Autowired
    private NettyServer nettyServer;

    private static final Logger log = LoggerFactory.getLogger(RuoYiApplication.class);
    public static void main(String[] args) {
        SpringApplication.run(RuoYiApplication.class, args);
        System.out.println("---项目启动成功---");
    }

    @Override
    public void run(String... args) throws Exception {
        nettyServer.start();
    }
}

5、后续有增加的功能时候,再进行更新

文章参考:https://blog.51cto.com/u_16099206/6430191

Java基础之《netty(12)—netty入门》_java netty tcp_csj50的博客-CSDN博客

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
使用 SpringBoot 整合 Netty 实现 TCP 服务器可以让我们更方便地管理和部署我们的应用程序。下面是一些基本的步骤: 1. 创建一个 SpringBoot 项目,并添加 Netty 和相应的依赖。 2. 创建一个 Netty 服务类,实现 ChannelInboundHandlerAdapter 接口。在这个类中,你可以实现接收、处理和发送 TCP 消息的逻辑。 3. 通过 SpringBoot 的配置文件,配置 Netty 服务器的端口和其他参数。 4. 在 SpringBoot 的启动类中,使用 @Bean 注解将 Netty 服务类注册为 bean。 5. 启动 SpringBoot 应用程序,Netty 服务器将开始监听传入的连接。 下面是一个简单的示例: ``` // 服务类 @Component public class MyNettyServer extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 处理接收到的消息 ByteBuf buf = (ByteBuf) msg; String message = buf.toString(CharsetUtil.UTF_8); // 返回响应消息 String response = "Hello, " + message; ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes())); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // 处理异常 cause.printStackTrace(); ctx.close(); } } // 启动类 @SpringBootApplication public class MyApplication { @Autowired private MyNettyServer myNettyServer; @Value("${netty.port}") private int port; @PostConstruct public void start() throws Exception { // 创建 EventLoopGroup EventLoopGroup group = new NioEventLoopGroup(); try { // 创建 ServerBootstrap ServerBootstrap b = new ServerBootstrap(); b.group(group) .channel(NioServerSocketChannel.class) .localAddress(new InetSocketAddress(port)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { // 添加处理器 ch.pipeline().addLast(myNettyServer); } }); // 启动服务器 ChannelFuture f = b.bind().sync(); f.channel().closeFuture().sync(); } finally { // 关闭 EventLoopGroup group.shutdownGracefully().sync(); } } public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } // 配置文件 netty.port=8080 ``` 在这个例子中,我们创建了一个名为 `MyNettyServer` 的服务类,并实现了 `ChannelInboundHandlerAdapter` 接口。在 `channelRead` 方法中,我们处理接收到的消息,并返回响应消息。在 `exceptionCaught` 方法中,我们处理异常。 在启动类中,我们使用 `@Autowired` 注解将 `MyNettyServer` 注入到启动类中,并使用 `@Value` 注解获取配置文件中的端口号。在 `start` 方法中,我们创建了一个 `EventLoopGroup`,并使用 `ServerBootstrap` 创建了一个 Netty 服务器。然后,我们将 `MyNettyServer` 添加到 `SocketChannel` 的处理器中。最后,我们启动服务器,并在关闭服务器之前等待连接。 这只是一个简单的示例,你可以根据你的需求修改和扩展它。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值