Thread: Basic Netty 4.0 Server

Results 1 to 6 of 6
  1. #1 Basic Netty 4.0 Server 
    Banned
    Join Date
    Jul 2015
    Posts
    126
    Thanks given
    21
    Thanks received
    9
    Rep Power
    0
    Sorry this is more of a snippet but may be helpful to some users who are new to networking.

    Whilst I'm learning networking myself, I made the most basic RS2 netty server. If you're new to networking, or you want to use netty 4.0 for your applications but aren't sure how to get started you can use this as a reference. It's quite simple.

    Make sure to download the Netty 4.0 library

    http://netty.io/downloads.html

    You can also view my github page as well.

    https://github.com/Rust94/Basic-Nett...I%20Server/src

    Code:
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelOption;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    
    /**
     * The core class for an RS2 server
     * 
     * @author Rust
     */
    public class Server {
    
    	/**
    	 * Logging system used to log messages for the server
    	 */
    	private static final Logger logger = Logger.getLogger(Server.class
    			.getName());
    
    	/**
    	 * Main method for the server application
    	 * 
    	 * @param args
    	 *            The command-line arguments
    	 */
    	public static void main(String[] args) {
    		try {
    			new Server().init();
    		} catch (Throwable t) {
    			logger.log(Level.SEVERE, "Error while starting the server.", t);
    		}
    	}
    
    	/**
    	 * Creating an empty constructor
    	 */
    	public Server() throws Exception {
    		logger.log(Level.INFO, "RS2 Server initializing...");
    	}
    
    	/**
    	 * Initializes the Server Channel Handler
    	 * 
    	 * @throws InterruptedException
    	 */
    	public void init() throws InterruptedException {
    		EventLoopGroup bossGroup = new NioEventLoopGroup();
    		EventLoopGroup workerGroup = new NioEventLoopGroup();
    		try {
    
    			ServerBootstrap bootstrap = new ServerBootstrap();
    			bootstrap.group(bossGroup, workerGroup)
    				.channel(NioServerSocketChannel.class)
    				.childHandler(new ServiceChannelInitializer(new ChannelHandler()))
    				.option(ChannelOption.SO_BACKLOG, 128)
    				.childOption(ChannelOption.SO_KEEPALIVE, true);
    
    			logger.log(Level.INFO, "Binding to port " + NetworkConstants.PORT);
    			ChannelFuture f = bootstrap.bind(NetworkConstants.PORT).sync();
    			logger.log(Level.INFO, "Server Online and bound to port "
    					+ NetworkConstants.PORT);
    			f.channel().closeFuture().sync();
    		} finally {
    			workerGroup.shutdownGracefully();
    			bossGroup.shutdownGracefully();
    		}
    	}
    
    }
    ChannelHandler

    Code:
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import io.netty.channel.SimpleChannelInboundHandler;
    
    /**
     * An extension of {@link SimpleChannelInboundHandler} which is useful in this case
     * vs {@link ChannelInboundHandler} because {@link SimpleChannelInboundHandler} releases the objects
     * right away. {@link ChannelInboundHandlerAdapter} does not.
     * 
     * @author Rust
     */
    public class ChannelHandler extends SimpleChannelInboundHandler<Message> {
    
    	@Override
    	protected void channelRead0(ChannelHandlerContext arg0, Message arg1)
    			throws Exception {
    		
    	}
    
    }
    ServiceChannelInitializer

    Code:
    package core.net;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.ChannelPipeline;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.handler.timeout.ReadTimeoutHandler;
    
    /**
     * A {@link ChannelInitializer} for the service pipeline
     * 
     * @author Rust
     */
    public class ServiceChannelInitializer extends
    		ChannelInitializer<SocketChannel> {
    	
    	private final ChannelHandler handler;
    	
    	private static final Logger logger = Logger.getLogger(ServiceChannelInitializer.class.getName());
    
    	public ServiceChannelInitializer(ChannelHandler handler) {
    		this.handler = handler;
    	}
    
    	@Override
    	protected void initChannel(SocketChannel ch) throws Exception {
    		ChannelPipeline pipeline = ch.pipeline();
    		pipeline.addLast("timeout", new ReadTimeoutHandler(10));
    		//ch.pipeline().addLast("encoder", new RS2Encoder());
    		//ch.pipeline().addLast("decoder", new RS2LoginProtocol());
    		pipeline.addLast("handler", handler);
    		logger.log(Level.INFO, "Connection recieved from " + ch.remoteAddress().getAddress());		
    	}
    
    }
    An Interface PacketType

    Code:
    package core.net.message;
    
    import core.net.ChannelHandler;
    
    /**
     * We can use an interface to have objects implement this so that any class that
     * implements this interface will be able to pass through the {@link ChannelHandler}
     * as a message.
     * @author Rust
     */
    public interface PacketType {
    
    }
    NetworkConstants

    Code:
    /**
     * Class consisting of only network constants
     */
    public class NetworkConstants {
    	
    	public static final int PORT = 43594;
    	
    }
    Reply With Quote  
     

  2. #2  
    Donator


    Join Date
    Jan 2014
    Posts
    1,652
    Thanks given
    428
    Thanks received
    501
    Rep Power
    221
    Thanks, will come in handy
    Reply With Quote  
     

  3. #3  
    Banned
    Join Date
    Jul 2012
    Age
    27
    Posts
    996
    Thanks given
    646
    Thanks received
    266
    Rep Power
    0
    Thanks bud, this is pretty neat
    Reply With Quote  
     

  4. #4  
    Reverse Engineering

    freeezr's Avatar
    Join Date
    Dec 2011
    Posts
    1,067
    Thanks given
    288
    Thanks received
    444
    Rep Power
    401
    You can also use chaining on the server bootstrap.

    Code:
    		bootstrap
    				.group(group)
    				.channel(NioServerSocketChannel.class)
    				.handler(new LoggingHandler(LogLevel.INFO))
    				.childHandler(new ChannelInitializer<NioSocketChannel>() {
    
    					@Override
    					protected void initChannel(NioSocketChannel ch)
    							throws Exception {
    						ChannelPipeline pipeline = ch.pipeline();
    
    						pipeline.addLast(HandshakeDecoder.class.getName(),
    								new HandshakeDecoder());
    						pipeline.addLast(IdleStateHandler.class.getName(),
    								new IdleStateHandler(15, 0, 0));
    						pipeline.addLast("handler", new GameChannelHandler(
    								server));
    					}
    
    				}).option(ChannelOption.SO_BACKLOG, 128)
    				.childOption(ChannelOption.TCP_NODELAY, true);
    Id also suggest doing the channel initializer like mine, as its one less class to worry about.

    Oh and btw, for you channel handler, if you only going to read a certain type of message, you can use SimpleChannelInboundHandler<I>

    Also, this is a good feature it have, at least for starting out/debugging:
    Code:
    		ResourceLeakDetector.setLevel(Level.ADVANCED);
    As you can see its a leak detector

    Attached image
    Reply With Quote  
     

  5. Thankful user:


  6. #5  
    Registered Member
    Velocity's Avatar
    Join Date
    Jan 2009
    Age
    28
    Posts
    2,028
    Thanks given
    1,013
    Thanks received
    2,376
    Rep Power
    4112
    Quote Originally Posted by Leon_ View Post
    You can also use chaining on the server bootstrap.

    Code:
    		bootstrap
    				.group(group)
    				.channel(NioServerSocketChannel.class)
    				.handler(new LoggingHandler(LogLevel.INFO))
    				.childHandler(new ChannelInitializer<NioSocketChannel>() {
    
    					@Override
    					protected void initChannel(NioSocketChannel ch)
    							throws Exception {
    						ChannelPipeline pipeline = ch.pipeline();
    
    						pipeline.addLast(HandshakeDecoder.class.getName(),
    								new HandshakeDecoder());
    						pipeline.addLast(IdleStateHandler.class.getName(),
    								new IdleStateHandler(15, 0, 0));
    						pipeline.addLast("handler", new GameChannelHandler(
    								server));
    					}
    
    				}).option(ChannelOption.SO_BACKLOG, 128)
    				.childOption(ChannelOption.TCP_NODELAY, true);
    Id also suggest doing the channel initializer like mine, as its one less class to worry about.

    Oh and btw, for you channel handler, if you only going to read a certain type of message, you can use SimpleChannelInboundHandler<I>

    Also, this is a good feature it have, at least for starting out/debugging:
    Code:
    		ResourceLeakDetector.setLevel(Level.ADVANCED);
    As you can see its a leak detector
    wtf why would you want to use that leak detector while not using the built-in native jemalloc'd buffers which can leak as opposed to the other ones which just get gced?
    xxxxxxx
    Reply With Quote  
     

  7. #6  
    ZzzzZzzzzZzzzzZzzz
    Shoutout's Avatar
    Join Date
    Sep 2014
    Posts
    259
    Thanks given
    19
    Thanks received
    7
    Rep Power
    11
    Quote Originally Posted by Velocity View Post
    -
    I love how u quote Coone in ur sig, Velocity
    Reply With Quote  
     


Thread Information
Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)


User Tag List

Similar Threads

  1. Basic Netty Framework
    By Nice Day in forum Downloads
    Replies: 22
    Last Post: 05-30-2016, 01:34 PM
  2. netty client and server chat
    By kl3men in forum Application Development
    Replies: 0
    Last Post: 09-13-2010, 05:08 PM
  3. Private Server - Basic's
    By Soulze in forum Tutorials
    Replies: 4
    Last Post: 04-05-2008, 04:22 PM
  4. Basic Server Creation
    By confusedrlly in forum Tutorials
    Replies: 9
    Last Post: 02-07-2008, 06:09 PM
Posting Permissions
  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •