我在使用EmbeddedChannel处理用于HttpDecoder的DatagramPacket以用作ByteBuf方面做错了什么:
question: using netty HttpObjectDecoder with DatagramPacket to decode SSDP message
我使用简单的MessageToMessageDecoder将ByteBuf激发到EmbeddedChannel:
public class UdpSsdpDecoder extends MessageToMessageDecoder<DatagramPacket>{
private EmbeddedChannel m2sBridge;
public UdpSsdpDecoder(EmbeddedChannel m2sBridge) {
this.m2sBridge = m2sBridge;
}
@Override
protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception {
ByteBuf buf = msg.content();
m2sBridge.writeInbound(buf);
}
EmbeddedChannel收到消息:
Sep 12, 2014 9:55:29 AM io.netty.handler.logging.LoggingHandler channelRead
INFO: [id: 0x5b99b997, /0.0.0.0:1900] RECEIVED: DatagramPacket(/10.1.1.12:49155 => /0.0.0.0:1900, SimpleLeakAwareByteBuf(UnpooledUnsafeDirectByteBuf(ridx: 0, widx: 133, cap: 2048))), 133B
...
Sep 12, 2014 9:55:29 AM io.netty.handler.logging.LoggingHandler channelRead
INFO: [id: 0x1f759b61, embeded => embeded] RECEIVED: 133B
但是channelReadComplete正在触发而不是messageReceived(我正在使用5.0 API):
public class SsdpRequestHandler extends SimpleChannelInboundHandler<Object> {
public void messageReceived(ChannelHandlerContext ctx, Object request) throws Exception {
System.out.println(request.toString());
}
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
}
***其余代码的关键位***
//from class with main
private EmbeddedChannel m2sBridge = new EmbeddedChannel();
public void NetStart() throws Exception {
System.out.println("Bootstrapping the discovery server...");
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioDatagramChannel.class)
.option(ChannelOption.SO_REUSEADDR, true)
.option(ChannelOption.IP_MULTICAST_TTL, 2)
.option(ChannelOption.IP_MULTICAST_LOOP_DISABLED, true)
.localAddress(this.port)
.handler(createInitializer(channelGroup));
//set the channel.
channel = (NioDatagramChannel) bootstrap.bind().sync().channel();
channel.joinGroup(this.multiCastInet, NetworkInterface.getByName(this.iNet)).syncUninterruptibly();
//set the bridge
m2sBridge.pipeline().addFirst(new LoggingHandler(LogLevel.INFO));
m2sBridge.pipeline().addLast(new SsdpRequestHandler());
}
public class DiscoveryServiceInitializer extends ChannelInitializer<Channel> {
private final ChannelGroup channelGroup;
private EmbeddedChannel m2sBridge;
public DiscoveryServiceInitializer(ChannelGroup channelGroup,
EmbeddedChannel m2sBridge) {
this.channelGroup = channelGroup;
this.m2sBridge = m2sBridge;
}
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addFirst(new LoggingHandler(LogLevel.INFO));
pipeline.addLast("m2sBridge", new UdpSsdpDecoder(m2sBridge));
}
}