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 public class TelnetServerHandler extends SimpleChannelUpstreamHandler {
36
37 private static final Logger logger = Logger.getLogger(
38 TelnetServerHandler.class.getName());
39
40 @Override
41 public void handleUpstream(
42 ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
43 if (e instanceof ChannelStateEvent) {
44 logger.info(e.toString());
45 }
46 super.handleUpstream(ctx, e);
47 }
48
49 @Override
50 public void channelConnected(
51 ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
52
53 e.getChannel().write(
54 "Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n");
55 e.getChannel().write("It is " + new Date() + " now.\r\n");
56 }
57
58 @Override
59 public void messageReceived(
60 ChannelHandlerContext ctx, MessageEvent e) {
61
62
63
64 String request = (String) e.getMessage();
65
66
67 String response;
68 boolean close = false;
69 if (request.length() == 0) {
70 response = "Please type something.\r\n";
71 } else if (request.toLowerCase().equals("bye")) {
72 response = "Have a good day!\r\n";
73 close = true;
74 } else {
75 response = "Did you say '" + request + "'?\r\n";
76 }
77
78
79
80 ChannelFuture future = e.getChannel().write(response);
81
82
83
84 if (close) {
85 future.addListener(ChannelFutureListener.CLOSE);
86 }
87 }
88
89 @Override
90 public void exceptionCaught(
91 ChannelHandlerContext ctx, ExceptionEvent e) {
92 logger.log(
93 Level.WARNING,
94 "Unexpected exception from downstream.",
95 e.getCause());
96 e.getChannel().close();
97 }
98 }