1. 程式人生 > >Netty5使用者手冊之二:使用netty實現Discard伺服器程式

Netty5使用者手冊之二:使用netty實現Discard伺服器程式

<span style="font-family:Microsoft YaHei;font-size:14px;">package com.zzj.nio.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * 拋棄訊息服務端
 * @author zzj
 * @date Oct 19, 2016 1:24:05 PM
 */
public class DiscardServer {

	/**埠號**/
	private int port;
	
	/**
	 * 建構函式
	 * @param port
	 */
	public DiscardServer(int port){
		this.port = port;
	}
	
	public static void main(String[] args) {
		int port = 9999;
		try {
			//開啟服務端接受訊息
			new DiscardServer(port).run();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 開啟伺服器
	 * @author zzj
	 * @throws InterruptedException 
	 */
	public void run() throws InterruptedException{
		EventLoopGroup bossGroup = new NioEventLoopGroup();//(1)
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();//(2)
			bootstrap.group(bossGroup, workerGroup)
			.channel(NioServerSocketChannel.class)//(3)
			.childHandler(new ChannelInitializer<SocketChannel>() {//(4)

				@Override
				protected void initChannel(SocketChannel channel) throws Exception {
					channel.pipeline().addLast(new DiscardServerHandler());
				}
			});
			bootstrap.option(ChannelOption.SO_BACKLOG, 128)//(5)
			.childOption(ChannelOption.SO_KEEPALIVE, true);//(6)
			
			//緊接著,繫結並且開始接受請求的連線
			ChannelFuture future = bootstrap.bind(port).sync();
			
			//等待直到伺服器socket被關閉,在這裡例子中,這個不會發生,但是你可以這樣寫
			future.channel().closeFuture().sync();
			
		}finally{
			
			//優雅的關閉
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
}
</span>
1.NioEventLoopGroup是一個使用者處理io操作的多執行緒event loop.Netty對於不同種類的傳輸提供了多種EventLoopGroup實現方式。在這個例