1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
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
51
52 final SslHandler sslHandler = ctx.getPipeline().get(SslHandler.class);
53
54
55 ChannelFuture handshakeFuture = sslHandler.handshake();
56 handshakeFuture.addListener(new Greeter(sslHandler));
57 }
58
59 @Override
60 public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
61
62
63 channels.remove(e.getChannel());
64 }
65
66 @Override
67 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
68
69
70 String request = (String) e.getMessage();
71
72
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
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
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
112
113 channels.add(future.getChannel());
114 } else {
115 future.getChannel().close();
116 }
117 }
118 }
119 }