使用java程序,监听tcp协议端口

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 lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 *<h1>监听tcp协议端口</h1>
 * @Author Zyh
 * @Date 2020/12/2
 **/
@Slf4j
@Component
public class RadarTransferServer implements ApplicationRunner {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    //监听的端口
    private static final int port = 9031;

    @Value("${third-interface-isprod}")
    String isprod;

    @Async
    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (isprod.equals("1")) {
            EventLoopGroup group = new NioEventLoopGroup();
            try {
                ServerBootstrap bootstrap = new ServerBootstrap();
                bootstrap.group(group);
                bootstrap.channel(NioServerSocketChannel.class);
                bootstrap.option(ChannelOption.SO_REUSEADDR, true);
                bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new MessageDecoder());
                    }
                });
                //缓冲区
                //bootstrap.option(ChannelOption.SO_BACKLOG,1024);
                //使用了Future来启动线程,并绑定了端口
                ChannelFuture future = bootstrap.bind(port).sync();
                logger.info("启动tcp服务器启动成功,正在监听端口:" + port);
                future.channel().closeFuture().await();//以异步的方式关闭端口
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                group.shutdownGracefully();
            }
        }
    }}

 

 

 

还有一个类:

import com.cscec.smart.platform.service.DeviceWaterLevelService;
import com.cscec.smart.platform.util.SpringUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
public class MessageDecoder extends StringDecoder {

//SpringUtil工具类,上个文章有,因为无法注入service、用工具获取
    @Resource
    DeviceWaterLevelService deviceWaterLevelService = SpringUtil.getApplicationContext()
            .getBean(DeviceWaterLevelService.class);

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        super.decode(ctx, msg, out);
        int i = msg.readableBytes();
//我这个tcp协议推送的数据,都是固定值,我就直接截取指定需要的字段的就可以
        byte[] deviceNoBytes = new byte[150];
        ByteBuf byteBuf = msg.readBytes(deviceNoBytes);
        String string = new String(deviceNoBytes);
        String deviceNo = string.substring(0, 15);
        String distance = string.substring(55, 60);
        String waterLevel = string.substring(61, 66);
        Boolean isWaterLevel = deviceWaterLevelService.saveDeviceWaterLevel(deviceNo, distance, waterLevel);
        log.info("==========保存机坪水位数据:{}",isWaterLevel);
    }
}

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值