我是 Netty 的新手,我决定从 4.0.0 开始,因为我认为它应该更好,因为它更新。我的服务器应用程序应该从 gps 设备接收数据,过程是这样的 - 首先我收到 2 个字节,这是设备 imei 的长度,然后我收到具有该长度的 imei,然后我应该发送 0x01 到设备,如果我想接受它的数据。在我的应答设备使用 AVL 协议向我发送 gps 数据后。现在我的服务器在没有 Netty 的情况下工作,我想将其更改为与 netty 一起工作。这就是我所做的:
我已经创建了这样的服务器类
public class BusDataReceiverServer {
private final int port;
private final Logger LOG = LoggerFactory.getLogger(BusDataReceiverServer.class);
public BusDataReceiverServer(int port) {
this.port = port;
}
public void run() throws Exception {
LOG.info("running thread");
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try{
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new BusDataReceiverInitializer());
b.bind(port).sync().channel().closeFuture().sync();
}catch (Exception ex){
LOG.info(ex.getMessage());
}
finally {
LOG.info("thread closed");
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
new BusDataReceiverServer(3129).run();
}
}
并创建了初始化类
public class BusDataReceiverInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast("imeiDecoder", new ImeiDecoder());
pipeline.addLast("busDataDecoder", new BusDataDecoder());
pipeline.addLast("encoder", new ResponceEncoder());
pipeline.addLast("imeiHandler", new ImeiReceiverServerHandler());
pipeline.addLast("busDataHandler", new BusDataReceiverServerHandler());
}
}
然后我创建了解码器和编码器以及 2 个处理程序。我的imeiDecoder 和编码器以及ImeiReceiverServerHandler 正在工作。这是我的 ImeiReceiverServerHandler
public class ImeiReceiverServerHandler extends ChannelInboundHandlerAdapter {
private final Logger LOG = LoggerFactory.getLogger(ImeiReceiverServerHandler.class);
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageList<Object> msgs) throws Exception {
MessageList<String> imeis = msgs.cast();
String imei = imeis.get(0);
ctx.write(Constants.BUS_DATA_ACCEPT);
ctx.fireMessageReceived(msgs);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx); //To change body of overridden methods use File | Settings | File Templates.
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause); //To change body of overridden methods use File | Settings | File Templates.
}
}
现在,接受后我不明白如何继续接收 gps 数据并将其转发给处理程序 BusDataReceiverServerHandler。如果有人可以帮助我或可以为我提供有用的文档,我将非常感激。或者,如果可以使用 Netty 3 做到这一点,我也将不胜感激。