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