View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.example.factorial;
17  
18  import io.netty.channel.ChannelHandlerContext;
19  import io.netty.channel.SimpleChannelInboundHandler;
20  
21  import java.math.BigInteger;
22  
23  /**
24   * Handler for a server-side channel.  This handler maintains stateful
25   * information which is specific to a certain channel using member variables.
26   * Therefore, an instance of this handler can cover only one channel.  You have
27   * to create a new handler instance whenever you create a new channel and insert
28   * this handler  to avoid a race condition.
29   */
30  public class FactorialServerHandler extends SimpleChannelInboundHandler<BigInteger> {
31  
32      private BigInteger lastMultiplier = new BigInteger("1");
33      private BigInteger factorial = new BigInteger("1");
34  
35      @Override
36      public void channelRead0(ChannelHandlerContext ctx, BigInteger msg) throws Exception {
37          // Calculate the cumulative factorial and send it to the client.
38          lastMultiplier = msg;
39          factorial = factorial.multiply(msg);
40          ctx.writeAndFlush(factorial);
41      }
42  
43      @Override
44      public void channelInactive(ChannelHandlerContext ctx) throws Exception {
45          System.err.printf("Factorial of %,d is: %,d%n", lastMultiplier, factorial);
46      }
47  
48      @Override
49      public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
50          cause.printStackTrace();
51          ctx.close();
52      }
53  }