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 org.jboss.netty.channel.ChannelEvent;
19 import org.jboss.netty.channel.ChannelFuture;
20 import org.jboss.netty.channel.ChannelFutureListener;
21 import org.jboss.netty.channel.ChannelHandlerContext;
22 import org.jboss.netty.channel.ChannelStateEvent;
23 import org.jboss.netty.channel.ExceptionEvent;
24 import org.jboss.netty.channel.MessageEvent;
25 import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
26
27 import java.net.InetAddress;
28 import java.util.Date;
29
30
31
32
33 public class TelnetServerHandler extends SimpleChannelUpstreamHandler {
34
35 @Override
36 public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
37 if (e instanceof ChannelStateEvent) {
38 System.err.println(e);
39 }
40 super.handleUpstream(ctx, e);
41 }
42
43 @Override
44 public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
45
46 e.getChannel().write("Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n");
47 e.getChannel().write("It is " + new Date() + " now.\r\n");
48 }
49
50 @Override
51 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
52
53
54
55 String request = (String) e.getMessage();
56
57
58 String response;
59 boolean close = false;
60 if (request.length() == 0) {
61 response = "Please type something.\r\n";
62 } else if ("bye".equals(request.toLowerCase())) {
63 response = "Have a good day!\r\n";
64 close = true;
65 } else {
66 response = "Did you say '" + request + "'?\r\n";
67 }
68
69
70
71 ChannelFuture future = e.getChannel().write(response);
72
73
74
75 if (close) {
76 future.addListener(ChannelFutureListener.CLOSE);
77 }
78 }
79
80 @Override
81 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
82 e.getCause().printStackTrace();
83 e.getChannel().close();
84 }
85 }