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);
}
}