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    *   http://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 org.jboss.netty.example.discard;
17  
18  import java.util.logging.Level;
19  import java.util.logging.Logger;
20  
21  import org.jboss.netty.buffer.ChannelBuffer;
22  import org.jboss.netty.channel.ChannelEvent;
23  import org.jboss.netty.channel.ChannelHandlerContext;
24  import org.jboss.netty.channel.ChannelStateEvent;
25  import org.jboss.netty.channel.ExceptionEvent;
26  import org.jboss.netty.channel.MessageEvent;
27  import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
28  
29  /**
30   * Handles a server-side channel.
31   */
32  public class DiscardServerHandler extends SimpleChannelUpstreamHandler {
33  
34      private static final Logger logger = Logger.getLogger(
35              DiscardServerHandler.class.getName());
36  
37      private long transferredBytes;
38  
39      public long getTransferredBytes() {
40          return transferredBytes;
41      }
42  
43      @Override
44      public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
45          if (e instanceof ChannelStateEvent) {
46              logger.info(e.toString());
47          }
48  
49          // Let SimpleChannelHandler call actual event handler methods below.
50          super.handleUpstream(ctx, e);
51      }
52  
53      @Override
54      public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
55          // Discard received data silently by doing nothing.
56          transferredBytes += ((ChannelBuffer) e.getMessage()).readableBytes();
57      }
58  
59      @Override
60      public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
61          // Close the connection when an exception is raised.
62          logger.log(
63                  Level.WARNING,
64                  "Unexpected exception from downstream.",
65                  e.getCause());
66          e.getChannel().close();
67      }
68  }