手游服务端框架之网关
网关介绍
游戏服务器的网关,主要是用于手机客户端与游戏业务服务端通信的中转器,负责接收来自手机客户端的请求协议,以及推送服务端的响应包。
在单一进程服务端架构里,网关跟游戏业务处理是在同一个进程里。为了提高通信吞吐量,一些服务端架构将网关作为一个独立进程。这种模式下,客户端请求全部由网关接收,再通过网关转发给服务端;另一方面,服务端下发的消息,也只能通过网关推送到客户端。由于只有客户端跟网关是一对一的socket连接,网关到服务端只需创建若干socket就可以完成全部通信任务,大大提高了服务端的负载能力。
本文讨论的为集成网关。
采用Java编写的服务器在选择通信框架技术上,要么选择Netty,要么选择Mina,很少有公司会去研发自己的通信框架。原因很简单,重新造轮子实现NIO服务器,开发成本非常高,需要自己去处理各种复杂的网络情况,诸如客户端重复接入,消息编解码,半包读写等情况。即使花费长时间编写出来的NIO框架投入到生产环境使用,等待框架稳定也要非常长的时间,而且一旦在生产环境出现问题,后果是非常严重的。
Mina和Netty这两个框架的作者好像是同一个人。个人感觉Mina更容易上手。这可能跟我先学Netty,对NIO框架有了一点皮毛认知有关(^_^)
本文选择的通信框架为Mina。
mina服务端代码示例
一个简单的Mina服务端通信demo是非常简单的,主要代码无非就是以下几行:
1. 创建NioSocketAcceptor,用于监听客户端连接;
2. 指定通信编解码处理器;
3. 指定处理业务逻辑器,主要是接受消息之后的业务逻辑;
4. 指定监听端口,启动NioSocket服务;
主要代码如下:
1 public void start() throws Exception { 2 3 IoBuffer.setUseDirectBuffer(false); 4 IoBuffer.setAllocator(new SimpleBufferAllocator()); 5 6 acceptor = new NioSocketAcceptor(pool); 7 acceptor.setReuseAddress(true); 8 acceptor.getSessionConfig().setAll(getSessionConfig()); 9 10 //暂时写死在代码里,后期使用独立配置文件 11 int port = 9527; 12 logger.info("socket启动端口为{},正在监听客户端的连接", port); 13 DefaultIoFilterChainBuilder filterChain = acceptor.getFilterChain(); 14 filterChain.addLast("codec", new ProtocolCodecFilter(MessageCodecFactory.getInstance())); 15 acceptor.setHandler( new IOHandler() );//指定业务逻辑处理器 16 acceptor.setDefaultLocalAddress(new InetSocketAddress(port) );//设置端口号 17 acceptor.bind();//启动监听 18 19 }
其中IoHandler继承自IoHandlerAdapter,负责处理链路的建立,摧毁,以及消息的接收。当收到消息之后,先不进行业务处理,暂时打印消息的内容。
import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IoSession; public class IoHandler extends IoHandlerAdapter { @Override public void sessionCreated(IoSession session) { //显示客户端的ip和端口 System.out.println(session.getRemoteAddress().toString()); } @Override public void messageReceived(IoSession session, Object data ) throws Exception { Message message = (Message)data; System.out.println("收到消息-->" + message); } }
网关主要处理客户端的链接建立,以及消息的接受与响应。而具体通信协议栈的设计,则涉及到数据编解码问题了。下面主要介绍消息序列化与反序列化库的选择,以及介绍Mina处理粘包拆包的解决方案。
私有协议栈定义
私有协议主要用于游戏项目内部客户端与服务端通信消息的格式定义。不同于http/tcp协议,私有协议只用于内部通信,所以不需要遵循公有协议标准。每个项目都使用自定义的通信协议,协议标准主要是开发方便,编解码速度快,通信字节量少等。
本文使用的消息定义如下:
- 消息头
- 消息体
import com.kingston.net.annotation.Protocol; /** * 通信消息体定义 */ public abstract class Message { public short getModule() { Protocol annotation = getClass().getAnnotation(Protocol.class); if (annotation != null) { return annotation.module(); } return 0; } public short getCmd() { Protocol annotation = getClass().getAnnotation(Protocol.class); if (annotation != null) { return annotation.cmd(); } return 0; } public String key() { return this.getModule() + "_" + this.getCmd(); } }
其中,MessageMeta类是一个注解,主要包含消息的元信息申明
/** * 消息的元信息 * @author kingston */ @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface MessageMeta { /** 消息所属模块号 */ short module(); /** 消息所属子类型 */ short cmd(); }
编码器设计
JProtobuf的编解码非常简单,对于一个我们定义的请求消息,ReqLoginMessage类的playerId,password两个字段带有MessageMeta注解。
/** * 请求-账号登录 * @author kingston */ @MessageMeta(module=Modules.LOGIN, cmd=LoginDataPool.REQ_LOGIN) public class ReqLoginMessage extends Message { /** 账号流水号 */ @Protobuf(order = 1) private long accountId; @Protobuf(order = 2) private String password; public long getAccountId() { return accountId; } public void setAccountId(long playerId) { this.accountId = playerId; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "ReqLoginMessage [accountId=" + accountId + ", password=" + password + "]"; } }
jprotobuf序列化与反序列化方法
import java.io.IOException; import junit.framework.Assert; import org.junit.Test; import com.baidu.bjf.remoting.protobuf.Codec; import com.baidu.bjf.remoting.protobuf.ProtobufProxy; import com.kingston.game.login.message.ReqLoginMessage; public class TestJProtobuf { @Test public void testRequest() { ReqLoginMessage request = new ReqLoginMessage(); request.setPlayerId(123456L); request.setPassword("kingston"); Codec<ReqLoginMessage> simpleTypeCodec = ProtobufProxy .create(ReqLoginMessage.class); try { // 序列化 byte[] bb = simpleTypeCodec.encode(request); // 反序列化 ReqLoginMessage request2 = simpleTypeCodec.decode(bb); Assert.assertTrue(request2.getPlayerId() == request.getPlayerId()); Assert.assertTrue(request2.getPassword().equals(request.getPassword())); } catch (IOException e) { e.printStackTrace(); } } }
编码器的完整代码如下:
import java.io.IOException; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolEncoder; import org.apache.mina.filter.codec.ProtocolEncoderOutput; import com.baidu.bjf.remoting.protobuf.Codec; import com.baidu.bjf.remoting.protobuf.ProtobufProxy; import com.kingston.net.Message; import com.kingston.net.MessageFactory; import com.kingston.net.SessionProperties; public class MessageEncoder implements ProtocolEncoder{ @Override public void dispose(IoSession arg0) throws Exception { } @Override public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { _encode(session, message, out); } public void _encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { CodecContext context = (CodecContext) session.getAttribute(SessionProperties.CONTEXT_KEY); if (context == null) { context = new CodecContext(); session.setAttribute(SessionProperties.CONTEXT_KEY, context); } IoBuffer buffer = writeMessage((Message) message); out.write(buffer); } private IoBuffer writeMessage(Message message) { //----------------消息协议格式------------------------- // packetLength | moduleId | cmd | body // int short short byte[] IoBuffer buffer = IoBuffer.allocate(CodecContext.WRITE_CAPACITY); buffer.setAutoExpand(true); //消息内容长度,先占个坑 buffer.putInt(0); short moduleId = message.getModule(); short cmd = message.getCmd(); //写入module类型 buffer.putShort(moduleId); //写入cmd类型 buffer.putShort(cmd); //写入具体消息的内容 byte[] body = null; Class<Message> msgClazz = (Class<Message>) MessageFactory.INSTANCE.getMessage(moduleId, cmd); try { Codec<Message> codec = ProtobufProxy.create(msgClazz); body = codec.encode(message); } catch (IOException e) { e.printStackTrace(); //logger } buffer.put(body); //回到buff字节数组头部 buffer.flip(); //重新写入包体长度 buffer.putInt(buffer.limit()-4); buffer.rewind(); return buffer; } }
解码器设计
1 import java.io.IOException; 2 3 import org.apache.mina.core.buffer.IoBuffer; 4 import org.apache.mina.core.session.IoSession; 5 import org.apache.mina.filter.codec.ProtocolDecoder; 6 import org.apache.mina.filter.codec.ProtocolDecoderOutput; 7 8 import com.baidu.bjf.remoting.protobuf.Codec; 9 import com.baidu.bjf.remoting.protobuf.ProtobufProxy; 10 import com.kingston.game.login.message.ReqLoginMessage; 11 import com.kingston.net.Message; 12 import com.kingston.net.MessageFactory; 13 import com.kingston.net.SessionProperties; 14 15 public class MessageDecoder implements ProtocolDecoder{ 16 17 public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { 18 _decode(session, in, out); 19 20 } 21 22 private void _decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) { 23 //必须保证每一个数据包的字节缓存都和session绑定在一起,不然就读取不了上一次剩余的数据了 24 CodecContext context = (CodecContext) session.getAttribute(SessionProperties.CONTEXT_KEY); 25 if (context == null) { 26 context = new CodecContext(); 27 session.setAttribute(SessionProperties.CONTEXT_KEY, context); 28 } 29 IoBuffer ioBuffer = context.getBuffer(); 30 ioBuffer.put(in); 31 32 //在循环里迭代,以处理数据粘包 33 for (; ;) { 34 ioBuffer.flip(); 35 //常量4表示消息body前面的两个short字段,一个表示moduel,一个表示cmd, 36 //一个short字段有两个字节,总共4个字节 37 if (ioBuffer.remaining() < 4) { 38 ioBuffer.compact(); 39 return; 40 } 41 //----------------消息协议格式------------------------- 42 // packetLength | moduleId | cmd | body 43 // int short short byte[] 44 int length = ioBuffer.getInt(); 45 int packLen = length + 4; 46 //大于消息body长度,说明至少有一条完整的message消息 47 if (ioBuffer.remaining() >= length) { 48 short moduleId = ioBuffer.getShort(); 49 short cmd = ioBuffer.getShort(); 50 byte[] body = new byte[length-4]; 51 ioBuffer.get(body); 52 53 Message msg = readMessage(moduleId, cmd, body); 54 out.write(msg); 55 56 if (ioBuffer.remaining() == 0) { 57 ioBuffer.clear(); 58 break; 59 } 60 ioBuffer.compact(); 61 } else{ 62 //数据包不完整,继续等待数据到达 63 ioBuffer.rewind(); 64 ioBuffer.compact(); 65 break; 66 } 67 } 68 } 69 70 private Message readMessage(short module, short cmd, byte[] body) { 71 Class<?> msgClazz = MessageFactory.INSTANCE.getMessage(module, cmd); 72 try { 73 Codec<?> codec = ProtobufProxy.create(msgClazz); 74 Message message = (Message) codec.decode(body); 75 76 return message; 77 } catch (IOException e) { 78 e.printStackTrace(); 79 } 80 return null; 81 } 82 83 public void dispose(IoSession arg0) throws Exception { 84 // TODO Auto-generated method stub 85 86 } 87 88 public void finishDecode(IoSession arg0, ProtocolDecoderOutput arg1) throws Exception { 89 // TODO Auto-generated method stub 90 91 } 92 93 }
浙公网安备 33010602011771号