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 public class QuoteOfTheMomentServerHandler extends SimpleChannelUpstreamHandler {
26
27 private static final Random random = new Random();
28
29
30 private static final String[] quotes = {
31 "Where there is love there is life.",
32 "First they ignore you, then they laugh at you, then they fight you, then you win.",
33 "Be the change you want to see in the world.",
34 "The weak can never forgive. Forgiveness is the attribute of the strong.",
35 };
36
37 private static String nextQuote() {
38 int quoteId;
39 synchronized (random) {
40 quoteId = random.nextInt(quotes.length);
41 }
42 return quotes[quoteId];
43 }
44
45 @Override
46 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
47 throws Exception {
48 String msg = (String) e.getMessage();
49 if (msg.equals("QOTM?")) {
50 e.getChannel().write("QOTM: " + nextQuote(), e.getRemoteAddress());
51 }
52 }
53
54 @Override
55 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
56 throws Exception {
57 e.getCause().printStackTrace();
58
59 }
60 }