4
votes

We need to broadcast an Object(Pojo) over UDP channel using Netty 4.0.0 binary.
In Netty 4.0.0 it allows us to use only DatagramPacket class to send UDP packet.
This class only accepts ByteBuf as an argument.

Is there any other way,we can send a Pojo over UDP channel ?

To further clarify,we were doing as follows:

Initializing settings for UDP channel

ConnectionlessBootstrap udpBootstrap;
udpBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(
                        new ObjectEncoder(),
                        new ObjectDecoder(new NettyElementInfo()),
                        new UDPBroadcastHandler());
            }
        });
        udpBootstrap.setOption("broadcast", true);
        //datagramChannel = (DatagramChannel) udpBootstrap.bind(new InetSocketAddress(udp_port));
        datagramChannel = (DatagramChannel) udpBootstrap.bind(new InetSocketAddress(0));

Here,NettyElementInfo implements Serializable and ClassResolver interfaces.We were trying to broadcast this pojo as follows:

channel.write(new NettyElementInfo(), 
                new InetSocketAddress("255.255.255.255", 9555));

At the receiving end, we were doing same as above for the Initialization part.However,in the handler were getting the Pojo as follows:

NettyElementInfo elementInfo = (NettyElementInfo)e.getMessage();

This was successfully done using netty 3.5.x

How to replicate this scenario using Netty 4.0.0. Please provide us with the sample code.

2
Hi I am facing same issue. Can you please help me as I am also implementing it in Netty 4.0.0.Shamse Alam

2 Answers

2
votes

I think you could just have a MessageToMessageDecoder/MessageToMessageEncoder that will encode/decode the DatagramPacket to a ByteBuf, which actual is nothing more then call DatagramPacket.content() for decode (just as example). After the Encoder/Decoder you can add the usual other ChannelHandlers that will handle the decoding of ByteBuf to a Pojo.

0
votes

In Netty 4, you have to pass around the address inside of your message until you're ready to create a DatagramPacket.

You can do this manually, or use the built-in DefaultAddressedEnvelope.

You can also use a DatagramPacketEncoder which wraps your MessageToMessageEncoder and creates DatagramPackets for you out of your AddressedEnvelopes and ByteBufs. This doesn't really add much convenience, so I can't say I recommend it.

pipeline.addLast (new ObjectEncoder());
...
channel.write(new NettyElementInfo(),  
            new InetSocketAddress("255.255.255.255", 9555));

becomes

pipeline.addLast (new DatagramPacketEncoder (new ObjectEncoder()));
...
channel.write(new DefaultAddressedEnvelope<>(new NettyElementInfo(), 
            new InetSocketAddress("255.255.255.255", 9555)));