View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
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   * Handles a server-side channel.
29   */
30  @Sharable
31  public class TelnetServerHandler extends SimpleChannelInboundHandler<String> {
32  
33      @Override
34      public void channelActive(ChannelHandlerContext ctx) throws Exception {
35          // Send greeting for a new connection.
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          // Generate and write a response.
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          // We do not need to write a ChannelBuffer here.
56          // We know the encoder inserted at TelnetPipelineFactory will do the conversion.
57          ChannelFuture future = ctx.write(response);
58  
59          // Close the connection after sending 'Have a good day!'
60          // if the client has sent 'bye'.
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  }