1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.example.telnet;
17
18 import java.net.InetAddress;
19 import java.util.Date;
20 import java.util.logging.Level;
21 import java.util.logging.Logger;
22
23 import org.jboss.netty.channel.ChannelEvent;
24 import org.jboss.netty.channel.ChannelFuture;
25 import org.jboss.netty.channel.ChannelFutureListener;
26 import org.jboss.netty.channel.ChannelHandlerContext;
27 import org.jboss.netty.channel.ChannelStateEvent;
28 import org.jboss.netty.channel.ExceptionEvent;
29 import org.jboss.netty.channel.MessageEvent;
30 import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
31
32
33
34
35
36
37
38
39
40 public class TelnetServerHandler extends SimpleChannelUpstreamHandler {
41
42 private static final Logger logger = Logger.getLogger(
43 TelnetServerHandler.class.getName());
44
45 @Override
46 public void handleUpstream(
47 ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
48 if (e instanceof ChannelStateEvent) {
49 logger.info(e.toString());
50 }
51 super.handleUpstream(ctx, e);
52 }
53
54 @Override
55 public void channelConnected(
56 ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
57
58 e.getChannel().write(
59 "Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n");
60 e.getChannel().write("It is " + new Date() + " now.\r\n");
61 }
62
63 @Override
64 public void messageReceived(
65 ChannelHandlerContext ctx, MessageEvent e) {
66
67
68
69 String request = (String) e.getMessage();
70
71
72 String response;
73 boolean close = false;
74 if (request.length() == 0) {
75 response = "Please type something.\r\n";
76 } else if (request.toLowerCase().equals("bye")) {
77 response = "Have a good day!\r\n";
78 close = true;
79 } else {
80 response = "Did you say '" + request + "'?\r\n";
81 }
82
83
84
85 ChannelFuture future = e.getChannel().write(response);
86
87
88
89 if (close) {
90 future.addListener(ChannelFutureListener.CLOSE);
91 }
92 }
93
94 @Override
95 public void exceptionCaught(
96 ChannelHandlerContext ctx, ExceptionEvent e) {
97 logger.log(
98 Level.WARNING,
99 "Unexpected exception from downstream.",
100 e.getCause());
101 e.getChannel().close();
102 }
103 }