Unity3d实战之Unity3d网络游戏实战篇(9):协议
学习书籍《Unity3d网络游戏实战》 罗培羽著 机械工业出版社
本文是作者在学习过程中遇到的认为值得记录的点,因此引用的代码等资源基本出资罗培羽老师的书籍,如有侵权请联系,必删。
一套通用的服务端框架要支持不同游戏所使用的各种协议格式。所谓协议就是通信规则,例如:如果发送端直接发送一串数值数据给接收端,接收端并不知道这一串数据到底是用来做什么的,里面的数据代表了什么信息。而协议就是解决这一问题的一套规则,一套发送端和接收端都知道的规则。在要发送的数据前添加某些标志,发送端和接收端共同规定带有这个标志的数据的用途。这样,两端就可以对接收到的数据进行解析,并根据两者共同定立的规则来分辨所接收到的数据的用途。
所有的协议都有相同的方法:解码、编码、获取协议名等等,以此为基础,我们可以编写一个协议的基类:
using System;
namespace Server
{
public class ProtocolBase
{
/// <summary>
/// Decode the readBuff from start to start+length. Package readBuff as a protocol and return it.
/// </summary>
/// <param name="readBuff">Read buff.</param>
/// <param name="start">Type: int, decode begin from start.</param>
/// <param name="length">Type: int, decode from begin to start+length.</param>
public virtual ProtocolBase Decode(byte[] readBuff, int start, int length)
{
return new ProtocolBase ();
}
/// <summary>
/// Encode the protocol's content to binary array.
/// </summary>
public virtual byte[] Encode()
{
return new byte[] { };
}
/// <summary>
/// Return the protocol's name.
/// </summary>
/// <returns>The name.</returns>
public virtual string GetName()
{
return "";
}
/// <summary>
/// Return the protocol's description.
/// </summary>
/// <returns>The desc.</returns>