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.objectecho;
17  
18  import org.jboss.netty.channel.ChannelEvent;
19  import org.jboss.netty.channel.ChannelHandlerContext;
20  import org.jboss.netty.channel.ChannelState;
21  import org.jboss.netty.channel.ChannelStateEvent;
22  import org.jboss.netty.channel.ExceptionEvent;
23  import org.jboss.netty.channel.MessageEvent;
24  import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
25  
26  import java.util.concurrent.atomic.AtomicLong;
27  
28  /**
29   * Handles both client-side and server-side handler depending on which
30   * constructor was called.
31   */
32  public class ObjectEchoServerHandler extends SimpleChannelUpstreamHandler {
33  
34      private final AtomicLong transferredMessages = new AtomicLong();
35  
36      public long getTransferredMessages() {
37          return transferredMessages.get();
38      }
39  
40      @Override
41      public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
42          if (e instanceof ChannelStateEvent && ((ChannelStateEvent) e).getState() != ChannelState.INTEREST_OPS) {
43              System.err.println(e);
44          }
45          super.handleUpstream(ctx, e);
46      }
47  
48      @Override
49      public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
50          // Echo back the received object to the client.
51          transferredMessages.incrementAndGet();
52          e.getChannel().write(e.getMessage());
53      }
54  
55      @Override
56      public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
57          e.getCause().printStackTrace();
58          e.getChannel().close();
59      }
60  }