`

使用netty+spring搭建游戏框架

阅读更多
一、 java NIO简介
nio是java New IO的简称,在jdk1.4里提供的新api。Sun官方标榜的特性如下:
 为所有的原始类型提供(Buffer)缓存支持。
 字符集编码解码解决方案。
 Channel:一个新的原始I/O抽象。
 支持锁和内存映射文件的文件访问接口。
 提供多路(non-bloking)非阻塞式的高伸缩性网络I/O。
关于java NIO的实现部分不是本文讨论的重点,有兴趣的朋友可以访问JAVA夜无眠的博客JAVA NIO 实例。
二、 NIO框架简介
在Java社区,最知名的开源Java NIO框架要属Mina和Netty。实际上,Netty的作者原来就是Mina作者之一,所以可以想到,Netty和Mina在设计理念上会有很多共同点。而本文主要介绍的是使用netty搭建简单的游戏服务器,对于netty与mina的比较以及简单netty应用教程,将在其他文章中有所提及,敬请关注!
三、 netty游戏框架搭建
a) ServerBootstrap——netty框架的总入口
/** 
*  作者:chenpeng  
* E-mail:46731706@qq.com  
*  创建时间:2012-7-12 下午12:22:53  
*  类说明  netty game 
*/ 
public class ServerTest {


 public static void main(String[] args) {
  DOMConfigurator.configureAndWatch("config/log4j.xml");
  ApplicationContext factory = new FileSystemXmlApplicationContext(
    new String[] { "config/propholder.xml" });
  
     ServerBootstrap bootstrap = new ServerBootstrap( 
             new NioServerSocketChannelFactory( 
                     Executors.newCachedThreadPool(), 
                     Executors.newCachedThreadPool())); 
     ServerPipelineFactory httpServerPipelineFactory=(ServerPipelineFactory)factory.getBean("serverPipelineFactory");
     bootstrap.setPipelineFactory(httpServerPipelineFactory); 
     //启动端口 8888
     bootstrap.bind(new InetSocketAddress(8888)); 
     System.out.print("8888  server is starting……");

     
 }

}

b) ChannelPipeline
channelPipeline是一系列channelHandler的集合,他参照J2ee中的Intercepting Filter模式来实现的,让用户完全掌握如果在一个handler中处理事件,同时让pipeline里面的多个handler可以相互交互。
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;

import com.cp.netty.coder.Decoder;
import com.cp.netty.coder.Encoder;

/** 
* 	作者:chenpeng  
*	E-mail:46731706@qq.com  
* 	创建时间:2012-7-12 上午11:28:56  
* 	channelPipeline是一系列channelHandler的集合,他参照J2ee中的Intercepting Filter模式来实现的,
* 	让用户完全掌握如果在一个handler中处理事件,同时让pipeline里面的多个handler可以相互交互 
*/ 
public class ServerPipelineFactory implements ChannelPipelineFactory {
	public ServerHandler serverHandler;

	public ChannelPipeline getPipeline() throws Exception {
		ChannelPipeline pipeLine = Channels.pipeline();
		pipeLine.addLast("decoder", new Decoder(Integer.MAX_VALUE, 0, 4));
		pipeLine.addLast("encoder", new Encoder(4));
		pipeLine.addLast("handler", serverHandler);
		return pipeLine;
	}

	public ServerHandler getServerHandler() {
		return serverHandler;
	}

	public void setServerHandler(ServerHandler serverHandler) {
		this.serverHandler = serverHandler;
	}

}


c) Decoder——消息解码器
Decoder解码器继承于FrameDecoder,FrameDecoder是Netty codec包中的辅助类,它是个ChannelUpstreamHandler,decode方法是FrameDecoder子类需要实现的。在本程序采用的是LengthFieldBasedFrameDecoder。LengthFieldBasedFrameDecoder是基于长度字段的解码器。如果协议格式类似“内容长度”+内容、“固定头”+“内容长度”+动态内容这样的格式,就可以使用该解码器 。至于其他类型的解码器,这里不再一一介绍。
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder;


/** 
* 	作者:chenpeng  
*	E-mail:46731706@qq.com  
* 	创建时间:2012-7-12 上午11:22:14  
* 	协议解码器  
*/ 
public class Decoder extends LengthFieldBasedFrameDecoder {
	// 第一个参数为信息最大长度,超过这个长度回报异常,
	// 第二参数为长度属性的起始(偏移)位,我们的协议中长度是0到第3个字节,所以这里写0,
	// 第三个参数为“长度属性”的长度,我们是4个字节,所以写4,
	// 第四个参数为长度调节值,在总长被定义为包含包头长度时,修正信息长度,
	// 第五个参数为跳过的字节数,根据需要我们跳过前4个字节,以便接收端直接接受到不含“长度属性”的内容。

	public Decoder(int maxFrameLength, int lengthFieldOffset,
			int lengthFieldLength) {
		super(maxFrameLength, lengthFieldOffset, lengthFieldLength);
	}

	@Override
	protected Object decode(ChannelHandlerContext ctx, Channel channel,
			ChannelBuffer buffer) throws Exception {
		ChannelBuffer buffs = (ChannelBuffer)super.decode(ctx, channel, buffer); 
		return buffs;
	}

}

d) ServerHandler——消息分发器
在介绍这个类之前,先对几个概念进行简要说明:
1. Channel:channel 是负责数据读、写的对象。channel是双向的,既可以write 也可以read。而且在NIO中用户不应该直接从channel中读写数据,而是应该通过buffer,通过buffer再将数据读写到channel中。
一个channel 可以提供给用户下面几个信息
(1)channel的当前状态,比如open 还是closed
(2)ChannelConfig对象,表示channel的一些参数,比如bufferSize
(3)channel支持的所有i/o操作(比如read,write,connect.bind)
2. channelEvent:ChannelEvent广义的认为Channel相关的事件处理。他分为Upstream events和downstream events两大块。如果以服务器端为主体,那么client到server的数据传输过程是Upstream,而server到client的数据传输过程则是downstream;以客户端为主体的过程正好相反。一下主要介绍以服务器端为主体的开发。
3. 常用的Upstream events包括
a) messageReceived:信息被接受时 ---MessageEvent
b) exceptionCaught:产生异常时 ---ExceptionEvent
c) channelOpen:channel被开启时 ---ChannelStateEvent
d) channelClosed:channel被关闭时 ---ChannelStateEvent
e) channelBound:channel被开启并准备去连接但还未连接上的时候 ---ChannelStateEvent
f) channelUnbound:channel被开启不准备去连接时候 ---ChannelStateEvent
g) channelConnected:channel被连接上的时候 ---ChannelStateEvent
h) channelDisconnected:channel连接断开的时候 ---ChannelStateEvent
在本游戏架构里,ServerHandler扮演着创建线程、验证消息、分发消息的重要角色,程序如下:
import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.log4j.Logger;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import com.cp.game.HandlerDispatcher;
import com.cp.game.domain.MessageQueue;
import com.cp.netty.domain.GameRequest;

/** 
* 	作者:chenpeng  
*	E-mail:46731706@qq.com  
* 	创建时间:2012-7-12 下午12:02:52  
* 	游戏协议接收分发器 
*/ 
public class ServerHandler extends SimpleChannelUpstreamHandler {
	public Logger log = Logger.getLogger(this.getClass());
	public static HandlerDispatcher handlerDispatcher;


	public void init() {
		new Thread(handlerDispatcher).start();
	}

	

	/* (non-Javadoc)
	 * @see org.jboss.netty.channel.SimpleChannelUpstreamHandler#channelConnected(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent)
	 *	建立一个新channel
	 */
	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		log.debug("进来一个channel:" + ctx.getChannel().getId());
		MessageQueue messageQueue = new MessageQueue(
				new ConcurrentLinkedQueue<GameRequest>());
		handlerDispatcher.addMessageQueue(ctx.getChannel().getId(), messageQueue);

	}

	/* (non-Javadoc)
	 * @see org.jboss.netty.channel.SimpleChannelUpstreamHandler#channelDisconnected(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ChannelStateEvent)
	 *	玩家主动关闭channel
	 */
	@Override
	public void channelDisconnected(ChannelHandlerContext ctx,
			ChannelStateEvent e) throws Exception {
		log.error("关掉一个channel:" + ctx.getChannel().getId());
		handlerDispatcher.removeMessageQueue(e.getChannel().getId().toString());
		e.getChannel().close();
	}

	/* (non-Javadoc)
	 * @see org.jboss.netty.channel.SimpleChannelUpstreamHandler#exceptionCaught(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.ExceptionEvent)
	 *	玩家被动关闭channel
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		log.error("出异常啦……" + ctx.getChannel().getId());
		e.getCause().printStackTrace();
		handlerDispatcher.removeMessageQueue(e.getChannel().getId().toString());
		e.getChannel().close();
	}

	/* (non-Javadoc)
	 * @see org.jboss.netty.channel.SimpleChannelUpstreamHandler#messageReceived(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.MessageEvent)
	 *	消息接收处理器
	 */
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		ChannelBuffer buffs = (ChannelBuffer) e.getMessage();
		buffs.skipBytes(4);// 越过dataLength的字节
		byte[] decoded = new byte[buffs.readableBytes()];
		buffs.readBytes(decoded);
		GameRequest gameRequest = new GameRequest(e.getChannel(), decoded);

		// 通知回调协议
		handlerDispatcher.addMessage(gameRequest);
	}

	public HandlerDispatcher getHandlerDispatcher() {
		return handlerDispatcher;
	}

	public void setHandlerDispatcher(HandlerDispatcher handlerDispatcher) {
		ServerHandler.handlerDispatcher = handlerDispatcher;
	}

}

需要注意的是:HandlerDispatcher是一个多线程处理器,用于处理游戏逻辑请求。这部分功能可根据用户的不同需求进行定制。
e) Encoder——消息编码器
消息编码器主要完成的是对游戏逻辑处理器返回的数据进行编码,组合成符合客户端规范的消息格式并发送。
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.LengthFieldPrepender;

import com.cp.netty.domain.GameResponse;

/** 
* 	作者:chenpeng  
*	E-mail:46731706@qq.com  
* 	创建时间:2012-7-12 上午11:43:11  
* 	类说明  
*/ 
public class Encoder extends LengthFieldPrepender {

	public Encoder(int lengthFieldLength) {
		super(lengthFieldLength);
	}

	@Override
	protected Object encode(ChannelHandlerContext cxt, Channel channel,
			Object msg) throws Exception {
		
		ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(channel.getConfig().getBufferFactory());
		GameResponse response = (GameResponse) msg;
		buffer.writeInt(response.getRtMessage().length+20);
		buffer.writeInt(response.getCommondId());
		buffer.writeInt(response.getPlayerId());
		buffer.writeInt(response.getCommandType());
		buffer.writeLong(response.getTime());
		System.out.println("send message "+response.getCommondId());
		buffer.writeBytes(response.getRtObj().getBytesM());
		return buffer;

	}

}

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation=" 
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<bean id="serverPipelineFactory"
		class="com.cp.netty.ServerPipelineFactory"
		scope="prototype">
		<property name="serverHandler" ref="appHandler"></property>
	</bean>

	<bean id="appHandler" class="com.cp.netty.ServerHandler"
		init-method="init">
		<property name="handlerDispatcher" ref="handlerDispatcher" />
	</bean>
	<bean id="handlerDispatcher"
		class="com.cp.game.HandlerDispatcher" init-method="init"
		destroy-method="stop">
		<property name="messageExecutor">
			<bean class="com.cp.netty.domain.FiexThreadPoolExecutor"
				destroy-method="shutdown">
				<constructor-arg
					value="${app.dispatcher.pool.corePoolSize}" />
				<constructor-arg
					value="${app.dispatcher.pool.maximumPoolSize}" />
				<constructor-arg
					value="${app.dispatcher.pool.keepAliveSecond}" />
			</bean>
		</property>
		<property name="sleepTime" value="${app.dispatcher.sleepTime}" />
		<property name="handlerMap" ref="serverHandlerMapping" />
	</bean>

	<bean id="serverMainController" class="com.cp.game.ServerMainHandler"
        abstract="true">
    </bean>
	
	   <bean id="serverHandlerMapping" class="java.util.HashMap">
        <constructor-arg>
            <map>
                <!-- 测试协议 -->
                <entry key="1000">
                    <bean
                        class="com.cp.game.handler.common.InitHandler"
                        parent="serverMainController">
                    </bean>
                </entry>
            </map>
        </constructor-arg>
    </bean>

</beans>
分享到:
评论
24 楼 liulehua_123 2017-11-06  
23 楼 heng123 2017-10-03  
netty等视频java.5d6b.com教程
22 楼 di1984HIT 2017-08-02  
学习了~~  
21 楼 zhoujieyaoqu 2017-06-20  
楼主的git  不能提交分支,有些看法,楼主看看。

首先对于堆外内存零copy的问题,楼主,采用的模式是io通信采用的netty框架默认的方式,目前netty4采用的是堆外内存,但是在业务的时候,使用的堆内存,所以会有一次拷贝,我构想,直接使用堆外内存,与io业务公用一份数据,在业务中不消亡数据

然后楼主的handler有线程安全问题,我们使用ConcurrentHashMap 的时候,只是这个map本身是线程安全的,并不是对它的操作是安全的,楼主有段代码,再为空的时候,直接new一个放进去的做法,这个在理论上来说,非线程安全的。
20 楼 cpjsjxy 2014-11-26  
cys1357 写道
楼主,想请教一下,服务端将channal保存起来,用来实时写回数据到客户端,channnal本身是由框架管理的,当连接数很多时是否会被框架释放掉,而保存的副本却没有释放,从而引起一些异常现象,比如连接看上去没问题,但两边却不能传数据。我是初学服务器编程,可能基本概念不是很清楚,求指导。


没遇到过这种情况。
19 楼 cys1357 2014-11-24  
楼主,想请教一下,服务端将channal保存起来,用来实时写回数据到客户端,channnal本身是由框架管理的,当连接数很多时是否会被框架释放掉,而保存的副本却没有释放,从而引起一些异常现象,比如连接看上去没问题,但两边却不能传数据。我是初学服务器编程,可能基本概念不是很清楚,求指导。
18 楼 cpjsjxy 2014-11-14  
bluky999 写道
cpjsjxy 写道
bluky999 写道
cpjsjxy 写道
bluky999 写道
netty 3 ?难怪不兼容。。。

这是2012年的博客了


  了解,呵


稍后发个基于netty4.0的版本


   

HandlerDispatcher 和 MessageQueue 可以发一下 


看4.0的版本吧
17 楼 bluky999 2014-11-14  
cpjsjxy 写道
bluky999 写道
cpjsjxy 写道
bluky999 写道
netty 3 ?难怪不兼容。。。

这是2012年的博客了


  了解,呵


稍后发个基于netty4.0的版本


   

HandlerDispatcher 和 MessageQueue 可以发一下 
16 楼 cpjsjxy 2014-11-13  
bluky999 写道
cpjsjxy 写道
bluky999 写道
netty 3 ?难怪不兼容。。。

这是2012年的博客了


  了解,呵


稍后发个基于netty4.0的版本
15 楼 bluky999 2014-11-12  
cpjsjxy 写道
bluky999 写道
netty 3 ?难怪不兼容。。。

这是2012年的博客了


  了解,呵
14 楼 cpjsjxy 2014-11-12  
bluky999 写道
netty 3 ?难怪不兼容。。。

这是2012年的博客了
13 楼 bluky999 2014-11-12  
netty 3 ?难怪不兼容。。。
12 楼 spde1988 2014-11-05  
没有看到jar文件? 还希望楼主能够分享下~
11 楼 HuiXiaoPi 2014-02-15  
为什么都是编译后的
10 楼 Jacarri_Chan 2014-01-17  
代码有问题:
buffer.writeInt(response.getPlayerId()); netty使用BigEndian:低位放在前面,高位放在后面。

StreamUtils.readInt(inCommandData);的readInt方法却是将前面的左移位变大.

----------------------------------------------------------------------------

改两个方法后,代码运行ok
	private void _writeData(long aValue, int aLength) {
		if (writepos + aLength > buffer.length) {
			_expand(writepos + aLength + 100);
		}
		int tmp = (aLength - 1) * 8;
		while (tmp >= 0) {
			buffer[writepos++] = (byte) ((aValue >> tmp) & 0xFF);
			tmp -= 8;
		}
		size += aLength;
	}


	public static int readInt(InputStream in) throws IOException {
		int b0 = readByte(in);
		int b1 = readByte(in);
		int b2 = readByte(in);
		int b3 = readByte(in);
		return ((b0 & 0xFF) << 24) | ((b1 & 0xFF) << 16) | ((b2 & 0xFF) << 8) | (b3 & 0xFF);
	}

9 楼 Jacarri_Chan 2014-01-15  
ApplicationContext factory = new FileSystemXmlApplicationContext( 
    new String[] { "config/propholder.xml" }); 

可以使用[ApplicationContext factory = new ClassPathXmlApplicationContext(new String[] { "propholder.xml" });]

好处是propholder.xml放在classpath中就可以啦
8 楼 aaacccbbb 2013-08-22  
jar 包呢
7 楼 cpjsjxy 2013-05-22  
leehui1983 写道
请问ServerHandler的init()方法在哪里调用?


配置文件里加载时调用的!
6 楼 leehui1983 2013-03-26  
请问ServerHandler的init()方法在哪里调用?
5 楼 nocb 2013-03-06  
先谢了, 回去试试看

相关推荐

Global site tag (gtag.js) - Google Analytics