使用java程式,監聽tcp協議埠

Four-Tiger發表於2020-12-02
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);
    }
}

 

相關文章