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
25 import io.netty.util.concurrent.GlobalEventExecutor;
26
27
28
29
30
31 public class SecureChatServerHandler extends SimpleChannelInboundHandler<String> {
32
33 static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
34
35 @Override
36 public void channelActive(final ChannelHandlerContext ctx) {
37
38
39 ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(future -> {
40 ctx.writeAndFlush(
41 "Welcome to secure chat service!\n");
42 ctx.writeAndFlush(
43 "Your session is protected by " +
44 ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite() +
45 " cipher suite.\n");
46
47 channels.add(ctx.channel());
48 });
49 }
50
51 @Override
52 public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
53
54 for (Channel c: channels) {
55 if (c != ctx.channel()) {
56 c.writeAndFlush("[" + ctx.channel().remoteAddress() + "] " + msg + '\n');
57 } else {
58 c.writeAndFlush("[you] " + msg + '\n');
59 }
60 }
61
62
63 if ("bye".equals(msg.toLowerCase())) {
64 ctx.close();
65 }
66 }
67
68 @Override
69 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
70 cause.printStackTrace();
71 ctx.close();
72 }
73 }