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.netty5.example.telnet;
17  
18  import io.netty5.channel.ChannelFutureListeners;
19  import io.netty5.channel.ChannelHandlerContext;
20  import io.netty5.channel.SimpleChannelInboundHandler;
21  import io.netty5.util.concurrent.Future;
22  
23  import java.net.InetAddress;
24  import java.util.Date;
25  
26  /**
27   * Handles a server-side channel.
28   */
29  public class TelnetServerHandler extends SimpleChannelInboundHandler<String> {
30  
31      @Override
32      public boolean isSharable() {
33          return true;
34      }
35  
36      @Override
37      public void channelActive(ChannelHandlerContext ctx) throws Exception {
38          // Send greeting for a new connection.
39          ctx.write("Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n");
40          ctx.write("It is " + new Date() + " now.\r\n");
41          ctx.flush();
42      }
43  
44      @Override
45      public void messageReceived(ChannelHandlerContext ctx, String request) throws Exception {
46          // Generate and write a response.
47          String response;
48          boolean close = false;
49          if (request.isEmpty()) {
50              response = "Please type something.\r\n";
51          } else if ("bye".equals(request.toLowerCase())) {
52              response = "Have a good day!\r\n";
53              close = true;
54          } else {
55              response = "Did you say '" + request + "'?\r\n";
56          }
57  
58          // We do not need to write a ChannelBuffer here.
59          // We know the encoder inserted at TelnetPipelineFactory will do the conversion.
60          Future<Void> future = ctx.write(response);
61  
62          // Close the connection after sending 'Have a good day!'
63          // if the client has sent 'bye'.
64          if (close) {
65              future.addListener(ctx, ChannelFutureListeners.CLOSE);
66          }
67      }
68  
69      @Override
70      public void channelReadComplete(ChannelHandlerContext ctx) {
71          ctx.flush();
72      }
73  
74      @Override
75      public void channelExceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
76          cause.printStackTrace();
77          ctx.close();
78      }
79  }