Netty游戏服务器之一

所谓磨刀不误砍柴工,所以在搭建netty游戏服务器之前,我们先要把要准备的东西做好。

首先进入netty的官网下载最新版本的netty的jar包,http://netty.io/downloads.html,这里我下载的是netty-5.0.0.Alpha2.tar.bz2 版本的。

打开压缩包,找到all-in-one下面的netty-5.0.0.Alpha2.jar包。

打开我们的eclipse我们神圣的编辑器,然后新建一个File,取名叫lib,专门存放第三方的jar。

然后把之前的netty的jar拖到里面,然后再配置路径。

add jars吧这个包添加到路径里面。

ok,往事具备。接着我们开始netty编程之旅。先声明一点,读者需要对netty有所了解,不然可能看不懂我写的代码。

首先,我们先打个package,取名为com.netty.server,在包里面我们新建一个类GameServer,就是我们的服务器的主入口。

public class GameServer {
	public void bind(int port) throws Exception
	{
		EventLoopGroup bossGroup = new NioEventLoopGroup();//线程组
		EventLoopGroup workGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();//server启动管理配置
			b.group(bossGroup, workGroup)
			.channel(NioServerSocketChannel.class)
			.option(ChannelOption.SO_BACKLOG, 1024)//最大客户端连接数为1024
			.childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
				//这里我们先不写代码,这里主要是添加业务处理handler
				}
			});
			ChannelFuture f = b.bind(port).sync();
			if (f.isSuccess())
			{
				System.out.println("Server starts success at port:" + port);
			}
			f.channel().closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			bossGroup.shutdownGracefully();
			workGroup.shutdownGracefully();
		}
	}
	public static void main(String[] args) throws Exception
	{
		int port = 8080;
		new GameServer().bind(port);
	}
}

  

运行,就可以发现服务启动了。

原文地址:https://www.cnblogs.com/CaomaoUnity3d/p/4609154.html