1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty5.example.securechat;
17
18 import io.netty5.channel.Channel;
19 import io.netty5.channel.ChannelHandlerContext;
20 import io.netty5.channel.SimpleChannelInboundHandler;
21 import io.netty5.channel.group.ChannelGroup;
22 import io.netty5.channel.group.DefaultChannelGroup;
23 import io.netty5.handler.ssl.SslHandshakeCompletionEvent;
24 import io.netty5.util.concurrent.GlobalEventExecutor;
25
26 import java.net.InetAddress;
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 channelInboundEvent(ChannelHandlerContext ctx, Object evt) throws Exception {
37 if (evt instanceof SslHandshakeCompletionEvent) {
38 SslHandshakeCompletionEvent completionEvent = (SslHandshakeCompletionEvent) evt;
39
40
41 if (completionEvent.isSuccess()) {
42 ctx.writeAndFlush(
43 "Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n");
44 ctx.writeAndFlush(
45 "Your session is protected by " +
46 completionEvent.session().getCipherSuite() +
47 " cipher suite.\n");
48 channels.add(ctx.channel());
49 } else {
50 ctx.close();
51 }
52 }
53 super.channelInboundEvent(ctx, evt);
54 }
55
56 @Override
57 public void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
58
59 for (Channel c: channels) {
60 if (c != ctx.channel()) {
61 c.writeAndFlush("[" + ctx.channel().remoteAddress() + "] " + msg + '\n');
62 } else {
63 c.writeAndFlush("[you] " + msg + '\n');
64 }
65 }
66
67
68 if ("bye".equals(msg.toLowerCase())) {
69 ctx.close();
70 }
71 }
72
73 @Override
74 public void channelExceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
75 cause.printStackTrace();
76 ctx.close();
77 }
78 }