Advertisement
olemis

Coursera mobilecloud-001 : Netty echo server

Sep 21st, 2014
327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 4.23 KB | None | 0 0
  1.  
  2. /***
  3.  *
  4.  * Platform-independent reactive server program that accepts
  5.  * a connection from a client and echos back what the client sent .
  6.  *
  7.  * @author Olemis Lang
  8.  *
  9.  * p.s. compiled against netty-3.6.10.Final.jar
  10.  *
  11.  */
  12.  
  13. import java.net.InetSocketAddress;
  14. import java.util.Date;
  15. import java.util.concurrent.Executors;
  16.  
  17. import org.jboss.netty.bootstrap.ServerBootstrap;
  18. import org.jboss.netty.channel.*;
  19. import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
  20.  
  21. public class Program {
  22.  
  23.     /***
  24.      *
  25.      * Echo client data one chunk at a time .
  26.      *
  27.      * @author Olemis Lang
  28.      *
  29.      * This class is a Wrapper Facade encapsulating callbacks received from
  30.      * low-level sockets implementations. It also implements the Reactor pattern
  31.      * by acting as an Event handler processing ECHO protocol requests/responses.
  32.      *
  33.      */
  34.     static private class EchoServerHandler extends SimpleChannelUpstreamHandler {
  35.         /***
  36.          * Handle message received event by sending received data back to the client.
  37.          *
  38.          */
  39.         @Override
  40.         public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
  41.                 throws Exception {
  42.             // Write data back to the client
  43.             e.getChannel().write(e.getMessage());
  44.         }
  45.        
  46.         /***
  47.          * Print stack trace once an exception is detected
  48.          */
  49.         @Override
  50.         public void exceptionCaught(ChannelHandlerContext ctx,
  51.                 ExceptionEvent e) throws Exception {
  52.             // Print exception details onto standard error
  53.             e.getCause().printStackTrace();
  54.             // Close connection
  55.             e.getChannel().close();
  56.         }
  57.        
  58.         @Override
  59.         public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e)
  60.                 throws Exception {
  61.             System.out.println(new Date().toString() + " => connect from " +
  62.                 e.getChannel().getRemoteAddress().toString());
  63.         }
  64.        
  65.         @Override
  66.         public void channelDisconnected(ChannelHandlerContext ctx,
  67.                 ChannelStateEvent e) throws Exception {
  68.             System.out.println(new Date().toString() + " => disconnecting " +
  69.                     e.getChannel().getRemoteAddress().toString());
  70.         }
  71.     }
  72.    
  73.     public static void exit(String msg, int errcode) {
  74.         System.err.println(msg);
  75.         System.exit(errcode);
  76.     }
  77.    
  78.     public static void main(String[] args) {
  79.         if (args.length == 0) {
  80.             exit("Missing port number", 2);
  81.         }
  82.        
  83.         int port = 0;
  84.         try {
  85.             port = Integer.parseInt(args[0]);
  86.         }
  87.         catch (NumberFormatException e) {
  88.             exit("Port number expected", 1);
  89.         }
  90.        
  91.         // Channels and factories play the role of Acceptors
  92.         // by passively waiting for remote connection handshake
  93.         // and initializing upon request arrival the event
  94.         // handlers processing pipeline .
  95.         ChannelFactory f = new NioServerSocketChannelFactory(
  96.                 Executors.newCachedThreadPool(),
  97.                 Executors.newCachedThreadPool());
  98.         // Server bootstrap and channel instances act as
  99.         // Facade Wrapper since they
  100.         // provide access to low-level bind socket primitive.
  101.         // The former is a helper class with shortcuts to set up
  102.         // a server .
  103.         ServerBootstrap sb = new ServerBootstrap(f);
  104.         // Pipeline factories create channel pipelines acting as
  105.         // initiation dispatchers in Reactor pattern
  106.         // and are used to register, removing and dispatching
  107.         // event handlers.
  108.         sb.setPipelineFactory(new ChannelPipelineFactory() {
  109.            
  110.             @Override
  111.             public ChannelPipeline getPipeline() throws Exception {
  112.                 return Channels.pipeline(new EchoServerHandler());
  113.             }
  114.         });
  115.        
  116.         // Set TCP connection options
  117.         sb.setOption("child.tcpNoDelay", true);
  118.         sb.setOption("child.keepAlive",  true);
  119.         // Bind to socket , start listening for incoming requests
  120.         sb.bind(new InetSocketAddress(port));
  121.     }
  122.  
  123. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement