1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.example.securechat;
17
18 import io.netty.channel.Channel;
19 import io.netty.channel.ChannelHandlerContext;
20 import io.netty.channel.SimpleChannelInboundHandler;
21 import io.netty.channel.group.ChannelGroup;
22 import io.netty.channel.group.DefaultChannelGroup;
23 import io.netty.handler.ssl.SslHandler;
24 import io.netty.util.concurrent.Future;
25 import io.netty.util.concurrent.GenericFutureListener;
26 import io.netty.util.concurrent.GlobalEventExecutor;
27
28 import java.net.InetAddress;
29
30
31
32
33 public class SecureChatServerHandler extends SimpleChannelInboundHandler<String> {
34
35 static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
36
37 @Override
38 public void channelActive(final ChannelHandlerContext ctx) {
39
40
41 ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(
42 new GenericFutureListener<Future<Channel>>() {
43 @Override
44 public void operationComplete(Future<Channel> future) throws Exception {
45 ctx.writeAndFlush(
46 "Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n");
47 ctx.writeAndFlush(
48 "Your session is protected by " +
49 ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite() +
50 " cipher suite.\n");
51
52 channels.add(ctx.channel());
53 }
54 });
55 }
56
57 @Override
58 public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
59
60 for (Channel c: channels) {
61 if (c != ctx.channel()) {
62 c.writeAndFlush("[" + ctx.channel().remoteAddress() + "] " + msg + '\n');
63 } else {
64 c.writeAndFlush("[you] " + msg + '\n');
65 }
66 }
67
68
69 if ("bye".equals(msg.toLowerCase())) {
70 ctx.close();
71 }
72 }
73
74 @Override
75 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
76 cause.printStackTrace();
77 ctx.close();
78 }
79 }