1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty5.example.telnet;
17
18 import io.netty5.channel.ChannelFutureListeners;
19 import io.netty5.channel.ChannelHandlerContext;
20 import io.netty5.channel.SimpleChannelInboundHandler;
21 import io.netty5.util.concurrent.Future;
22
23 import java.net.InetAddress;
24 import java.util.Date;
25
26
27
28
29 public class TelnetServerHandler extends SimpleChannelInboundHandler<String> {
30
31 @Override
32 public boolean isSharable() {
33 return true;
34 }
35
36 @Override
37 public void channelActive(ChannelHandlerContext ctx) throws Exception {
38
39 ctx.write("Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n");
40 ctx.write("It is " + new Date() + " now.\r\n");
41 ctx.flush();
42 }
43
44 @Override
45 public void messageReceived(ChannelHandlerContext ctx, String request) throws Exception {
46
47 String response;
48 boolean close = false;
49 if (request.isEmpty()) {
50 response = "Please type something.\r\n";
51 } else if ("bye".equals(request.toLowerCase())) {
52 response = "Have a good day!\r\n";
53 close = true;
54 } else {
55 response = "Did you say '" + request + "'?\r\n";
56 }
57
58
59
60 Future<Void> future = ctx.write(response);
61
62
63
64 if (close) {
65 future.addListener(ctx, ChannelFutureListeners.CLOSE);
66 }
67 }
68
69 @Override
70 public void channelReadComplete(ChannelHandlerContext ctx) {
71 ctx.flush();
72 }
73
74 @Override
75 public void channelExceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
76 cause.printStackTrace();
77 ctx.close();
78 }
79 }