1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.example.factorial;
17
18 import org.jboss.netty.channel.ChannelEvent;
19 import org.jboss.netty.channel.ChannelHandlerContext;
20 import org.jboss.netty.channel.ChannelStateEvent;
21 import org.jboss.netty.channel.ExceptionEvent;
22 import org.jboss.netty.channel.MessageEvent;
23 import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
24
25 import java.math.BigInteger;
26 import java.util.Formatter;
27
28
29
30
31
32
33
34
35 public class FactorialServerHandler extends SimpleChannelUpstreamHandler {
36
37
38 private int lastMultiplier = 1;
39 private BigInteger factorial = new BigInteger(new byte[] { 1 });
40
41 @Override
42 public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
43 if (e instanceof ChannelStateEvent) {
44 System.err.println(e);
45 }
46 super.handleUpstream(ctx, e);
47 }
48
49 @Override
50 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
51
52 BigInteger number;
53 if (e.getMessage() instanceof BigInteger) {
54 number = (BigInteger) e.getMessage();
55 } else {
56 number = new BigInteger(e.getMessage().toString());
57 }
58 lastMultiplier = number.intValue();
59 factorial = factorial.multiply(number);
60 e.getChannel().write(factorial);
61 }
62
63 @Override
64 public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
65 System.err.println(new Formatter().format("Factorial of %,d is: %,d", lastMultiplier, factorial));
66 }
67
68 @Override
69 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
70 e.getCause().printStackTrace();
71 e.getChannel().close();
72 }
73 }