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 org.jboss.netty.channel.ChannelHandlerContext;
19 import org.jboss.netty.channel.ExceptionEvent;
20 import org.jboss.netty.channel.MessageEvent;
21 import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
22
23 import java.util.Random;
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 String msg = (String) e.getMessage();
48 if ("QOTM?".equals(msg)) {
49 e.getChannel().write("QOTM: " + nextQuote(), e.getRemoteAddress());
50 }
51 }
52
53 @Override
54 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
55 e.getCause().printStackTrace();
56
57 }
58 }