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.securechat;
17  
18  import org.jboss.netty.channel.Channel;
19  import org.jboss.netty.channel.ChannelEvent;
20  import org.jboss.netty.channel.ChannelFuture;
21  import org.jboss.netty.channel.ChannelFutureListener;
22  import org.jboss.netty.channel.ChannelHandlerContext;
23  import org.jboss.netty.channel.ChannelStateEvent;
24  import org.jboss.netty.channel.ExceptionEvent;
25  import org.jboss.netty.channel.MessageEvent;
26  import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
27  import org.jboss.netty.channel.group.ChannelGroup;
28  import org.jboss.netty.channel.group.DefaultChannelGroup;
29  import org.jboss.netty.handler.ssl.SslHandler;
30  
31  import java.net.InetAddress;
32  
33  /**
34   * Handles a server-side channel.
35   */
36  public class SecureChatServerHandler extends SimpleChannelUpstreamHandler {
37  
38      static final ChannelGroup channels = new DefaultChannelGroup();
39  
40      @Override
41      public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
42          if (e instanceof ChannelStateEvent) {
43              System.err.println(e);
44          }
45          super.handleUpstream(ctx, e);
46      }
47  
48      @Override
49      public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
50          // Get the SslHandler in the current pipeline.
51          // We added it in SecureChatPipelineFactory.
52          final SslHandler sslHandler = ctx.getPipeline().get(SslHandler.class);
53  
54          // Get notified when SSL handshake is done.
55          ChannelFuture handshakeFuture = sslHandler.handshake();
56          handshakeFuture.addListener(new Greeter(sslHandler));
57      }
58  
59      @Override
60      public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
61          // Unregister the channel from the global channel list
62          // so the channel does not receive messages anymore.
63          channels.remove(e.getChannel());
64      }
65  
66      @Override
67      public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
68  
69          // Convert to a String first.
70          String request = (String) e.getMessage();
71  
72          // Send the received message to all channels but the current one.
73          for (Channel c: channels) {
74              if (c != e.getChannel()) {
75                  c.write("[" + e.getChannel().getRemoteAddress() + "] " +
76                          request + '\n');
77              } else {
78                  c.write("[you] " + request + '\n');
79              }
80          }
81  
82          // Close the connection if the client has sent 'bye'.
83          if ("bye".equals(request.toLowerCase())) {
84              e.getChannel().close();
85          }
86      }
87  
88      @Override
89      public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
90          e.getCause().printStackTrace();
91          e.getChannel().close();
92      }
93  
94      private static final class Greeter implements ChannelFutureListener {
95  
96          private final SslHandler sslHandler;
97  
98          Greeter(SslHandler sslHandler) {
99              this.sslHandler = sslHandler;
100         }
101 
102         public void operationComplete(ChannelFuture future) throws Exception {
103             if (future.isSuccess()) {
104                 // Once session is secured, send a greeting.
105                 future.getChannel().write(
106                         "Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n");
107                 future.getChannel().write(
108                         "Your session is protected by " + sslHandler.getEngine().getSession().getCipherSuite() +
109                         " cipher suite.\n");
110 
111                 // Register the channel to the global channel list
112                 // so the channel received the messages from others.
113                 channels.add(future.getChannel());
114             } else {
115                 future.getChannel().close();
116             }
117         }
118     }
119 }