View Javadoc
1   /*
2    * Copyright 2016 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.codec;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.channel.AddressedEnvelope;
20  import io.netty.channel.ChannelHandlerContext;
21  import io.netty.channel.ChannelPipeline;
22  import io.netty.channel.ChannelPromise;
23  import io.netty.channel.socket.DatagramPacket;
24  import io.netty.util.internal.StringUtil;
25  import static io.netty.util.internal.ObjectUtil.checkNotNull;
26  
27  import java.net.InetSocketAddress;
28  import java.net.SocketAddress;
29  import java.util.List;
30  
31  /**
32   * An encoder that encodes the content in {@link AddressedEnvelope} to {@link DatagramPacket} using
33   * the specified message encoder. E.g.,
34   *
35   * <pre><code>
36   * {@link ChannelPipeline} pipeline = ...;
37   * pipeline.addLast("udpEncoder", new {@link DatagramPacketEncoder}(new {@code ProtobufEncoder}(...));
38   * </code></pre>
39   *
40   * Note: As UDP packets are out-of-order, you should make sure the encoded message size are not greater than
41   * the max safe packet size in your particular network path which guarantees no packet fragmentation.
42   *
43   * @param <M> the type of message to be encoded
44   */
45  public class DatagramPacketEncoder<M> extends MessageToMessageEncoder<AddressedEnvelope<M, InetSocketAddress>> {
46  
47      private final MessageToMessageEncoder<? super M> encoder;
48  
49      /**
50       * Create an encoder that encodes the content in {@link AddressedEnvelope} to {@link DatagramPacket} using
51       * the specified message encoder.
52       *
53       * @param encoder the specified message encoder
54       */
55      public DatagramPacketEncoder(MessageToMessageEncoder<? super M> encoder) {
56          this.encoder = checkNotNull(encoder, "encoder");
57      }
58  
59      @Override
60      public boolean acceptOutboundMessage(Object msg) throws Exception {
61          if (super.acceptOutboundMessage(msg)) {
62              @SuppressWarnings("rawtypes")
63              AddressedEnvelope envelope = (AddressedEnvelope) msg;
64              return encoder.acceptOutboundMessage(envelope.content())
65                      && (envelope.sender() instanceof InetSocketAddress || envelope.sender() == null)
66                      && envelope.recipient() instanceof InetSocketAddress;
67          }
68          return false;
69      }
70  
71      @Override
72      protected void encode(
73              ChannelHandlerContext ctx, AddressedEnvelope<M, InetSocketAddress> msg, List<Object> out) throws Exception {
74          assert out.isEmpty();
75  
76          encoder.encode(ctx, msg.content(), out);
77          if (out.size() != 1) {
78              throw new EncoderException(
79                      StringUtil.simpleClassName(encoder) + " must produce only one message.");
80          }
81          Object content = out.get(0);
82          if (content instanceof ByteBuf) {
83              // Replace the ByteBuf with a DatagramPacket.
84              out.set(0, new DatagramPacket((ByteBuf) content, msg.recipient(), msg.sender()));
85          } else {
86              throw new EncoderException(
87                      StringUtil.simpleClassName(encoder) + " must produce only ByteBuf.");
88          }
89      }
90  
91      @Override
92      public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) throws Exception {
93          encoder.bind(ctx, localAddress, promise);
94      }
95  
96      @Override
97      public void connect(
98              ChannelHandlerContext ctx, SocketAddress remoteAddress,
99              SocketAddress localAddress, ChannelPromise promise) throws Exception {
100         encoder.connect(ctx, remoteAddress, localAddress, promise);
101     }
102 
103     @Override
104     public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
105         encoder.disconnect(ctx, promise);
106     }
107 
108     @Override
109     public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
110         encoder.close(ctx, promise);
111     }
112 
113     @Override
114     public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
115         encoder.deregister(ctx, promise);
116     }
117 
118     @Override
119     public void read(ChannelHandlerContext ctx) throws Exception {
120         encoder.read(ctx);
121     }
122 
123     @Override
124     public void flush(ChannelHandlerContext ctx) throws Exception {
125         encoder.flush(ctx);
126     }
127 
128     @Override
129     public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
130         encoder.handlerAdded(ctx);
131     }
132 
133     @Override
134     public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
135         encoder.handlerRemoved(ctx);
136     }
137 
138     @Override
139     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
140         encoder.exceptionCaught(ctx, cause);
141     }
142 
143     @Override
144     public boolean isSharable() {
145         return encoder.isSharable();
146     }
147 }