78 lines
3.1 KiB
Java
78 lines
3.1 KiB
Java
package com.zhgd.netty.tcp.location;
|
||
|
||
import com.zhgd.netty.tcp.listener.BindListener;
|
||
import com.zhgd.netty.tcp.listener.CloseListener;
|
||
import io.netty.bootstrap.ServerBootstrap;
|
||
import io.netty.buffer.Unpooled;
|
||
import io.netty.channel.ChannelFuture;
|
||
import io.netty.channel.ChannelInitializer;
|
||
import io.netty.channel.ChannelOption;
|
||
import io.netty.channel.EventLoopGroup;
|
||
import io.netty.channel.nio.NioEventLoopGroup;
|
||
import io.netty.channel.socket.SocketChannel;
|
||
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
|
||
import lombok.extern.slf4j.Slf4j;
|
||
import org.springframework.beans.factory.annotation.Autowired;
|
||
import org.springframework.beans.factory.annotation.Qualifier;
|
||
import org.springframework.beans.factory.annotation.Value;
|
||
import org.springframework.context.annotation.Bean;
|
||
import org.springframework.stereotype.Component;
|
||
|
||
import javax.annotation.PostConstruct;
|
||
|
||
/**
|
||
* @author jt808协议解析-人员车辆定位
|
||
* @date 2020/03/17 15:45:35
|
||
*/
|
||
@Component
|
||
@Slf4j
|
||
public class TcpNettyServerJT808 {
|
||
@Autowired
|
||
private LocationMessageHandler locationMessageHandler;
|
||
@Autowired
|
||
private MessageEncoder messageEncoder;
|
||
@Autowired
|
||
@Qualifier("bossGroup")
|
||
private NioEventLoopGroup bossGroup;
|
||
|
||
@Autowired
|
||
@Qualifier("workerGroup")
|
||
private NioEventLoopGroup workerGroup;
|
||
|
||
@Value("${jt808.port:15003}")
|
||
int port;
|
||
|
||
@PostConstruct
|
||
private void startTcpServer() {
|
||
try {
|
||
ServerBootstrap serverBootstrap = new ServerBootstrap();
|
||
serverBootstrap.group(bossGroup, workerGroup)
|
||
.channel(NioServerSocketChannel.class)
|
||
.option(ChannelOption.SO_BACKLOG, 1024)
|
||
.childOption(ChannelOption.SO_KEEPALIVE, true)
|
||
.childHandler(new ChannelInitializer<SocketChannel>() {
|
||
@Override
|
||
protected void initChannel(SocketChannel socketChannel) throws Exception {
|
||
//添加自定义处理器
|
||
socketChannel.pipeline()
|
||
.addLast(new DelimiterBasedFrameDecoder(1100, Unpooled.copiedBuffer(new byte[]{JT808Const.PKG_DELIMITER}),
|
||
Unpooled.copiedBuffer(new byte[]{JT808Const.PKG_DELIMITER, JT808Const.PKG_DELIMITER})))
|
||
.addLast(new MessageDecoder())
|
||
.addLast(messageEncoder)
|
||
.addLast(locationMessageHandler);
|
||
}
|
||
});
|
||
//监听器,当服务绑定成功后执行
|
||
ChannelFuture channelFuture = serverBootstrap.bind(port).addListener(new BindListener());
|
||
//监听器,当停止服务后执行。
|
||
channelFuture.channel().closeFuture().addListener(new CloseListener());
|
||
} catch (Exception e) {
|
||
log.error("err:", e);
|
||
bossGroup.shutdownGracefully();
|
||
workerGroup.shutdownGracefully();
|
||
}
|
||
}
|
||
|
||
}
|