1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.example.qotm;
17
18 import java.util.Random;
19
20 import org.jboss.netty.channel.ChannelHandlerContext;
21 import org.jboss.netty.channel.ExceptionEvent;
22 import org.jboss.netty.channel.MessageEvent;
23 import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
24
25
26
27
28
29
30 public class QuoteOfTheMomentServerHandler extends SimpleChannelUpstreamHandler {
31
32 private static final Random random = new Random();
33
34
35 private static final String[] quotes = new String[] {
36 "Where there is love there is life.",
37 "First they ignore you, then they laugh at you, then they fight you, then you win.",
38 "Be the change you want to see in the world.",
39 "The weak can never forgive. Forgiveness is the attribute of the strong.",
40 };
41
42 private static String nextQuote() {
43 int quoteId;
44 synchronized (random) {
45 quoteId = random.nextInt(quotes.length);
46 }
47 return quotes[quoteId];
48 }
49
50 @Override
51 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
52 throws Exception {
53 String msg = (String) e.getMessage();
54 if (msg.equals("QOTM?")) {
55 e.getChannel().write("QOTM: " + nextQuote(), e.getRemoteAddress());
56 }
57 }
58
59 @Override
60 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
61 throws Exception {
62 e.getCause().printStackTrace();
63
64 }
65 }