View Javadoc
1   /*
2    * Copyright 2012 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.netty5.example.qotm;
17  
18  import io.netty5.buffer.api.Buffer;
19  import io.netty5.channel.ChannelHandlerContext;
20  import io.netty5.channel.SimpleChannelInboundHandler;
21  import io.netty5.channel.socket.DatagramPacket;
22  
23  import java.util.Random;
24  
25  import static java.nio.charset.StandardCharsets.UTF_8;
26  
27  public class QuoteOfTheMomentServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
28  
29      private static final Random random = new Random();
30  
31      // Quotes from Mohandas K. Gandhi:
32      private static final String[] quotes = {
33          "Where there is love there is life.",
34          "First they ignore you, then they laugh at you, then they fight you, then you win.",
35          "Be the change you want to see in the world.",
36          "The weak can never forgive. Forgiveness is the attribute of the strong.",
37      };
38  
39      private static String nextQuote() {
40          int quoteId;
41          synchronized (random) {
42              quoteId = random.nextInt(quotes.length);
43          }
44          return quotes[quoteId];
45      }
46  
47      @Override
48      public void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
49          System.err.println(packet);
50          if ("QOTM?".equals(packet.content().toString(UTF_8))) {
51              Buffer message = ctx.bufferAllocator().copyOf("QOTM: " + nextQuote(), UTF_8);
52              ctx.write(new DatagramPacket(message, packet.sender()));
53          }
54      }
55  
56      @Override
57      public void channelReadComplete(ChannelHandlerContext ctx) {
58          ctx.flush();
59      }
60  
61      @Override
62      public void channelExceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
63          cause.printStackTrace();
64          // We don't close the channel because we can keep serving requests.
65      }
66  }