public static void main(String[] args) throws Exception { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
// Configure the pipeline factory. bootstrap.setPipelineFactory(new TelnetServerPipelineFactory());
// Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); } }
public class TelnetServerPipelineFactory implements ChannelPipelineFactory {
public ChannelPipeline getPipeline() throws Exception { // Create a default pipeline implementation. ChannelPipeline pipeline = pipeline();
// Add the text line codec combination first, pipeline.addLast("framer", new DelimiterBasedFrameDecoder( 8192, Delimiters.lineDelimiter())); pipeline.addLast("decoder", new StringDecoder()); pipeline.addLast("encoder", new StringEncoder());
// and then business logic. pipeline.addLast("handler", new TelnetServerHandler());
return pipeline; } }
public class TelnetServerHandler extends SimpleChannelUpstreamHandler {
private static final Logger logger = Logger.getLogger( TelnetServerHandler.class.getName());
@Override public void handleUpstream( ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { logger.info(e.toString()); } super.handleUpstream(ctx, e); }
@Override public void channelConnected( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { // Send greeting for a new connection. e.getChannel().write( "Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n"); e.getChannel().write("It is " + new Date() + " now.\r\n"); }
@Override public void messageReceived( ChannelHandlerContext ctx, MessageEvent e) {
// Cast to a String first. // We know it is a String because we put some codec in TelnetPipelineFactory. String request = (String) e.getMessage();
// Generate and write a response. String response; boolean close = false; if (request.length() == 0) { response = "Please type something.\r\n"; } else if (request.toLowerCase().equals("bye")) { response = "Have a good day!\r\n"; close = true; } else { response = "Did you say '" + request + "'?\r\n"; }
// We do not need to write a ChannelBuffer here. // We know the encoder inserted at TelnetPipelineFactory will do the conversion. ChannelFuture future = e.getChannel().write(response);
// Close the connection after sending 'Have a good day!' // if the client has sent 'bye'. if (close) { future.addListener(ChannelFutureListener.CLOSE); } }
@Override public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e) { logger.log( Level.WARNING, "Unexpected exception from downstream.", e.getCause()); e.getChannel().close(); } }