1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
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
65 }
66 }