-
Notifications
You must be signed in to change notification settings - Fork 552
NetWorkManger 封装了常用的Socket连接方式(TCP,UDP),并内置了Json和Protocol协议,并提供接口以支持协议拓展。
NetworkManager
static void Init<TProtocol,TSocket>(ProtocolType protocolType)
初始化NetWorkManager,设定连接方式和通讯协议
TProtocol : INetworkInterface
TSocket : SocketBase
static void Dispose()
释放NetworkManager
static void SetServer(string IP, int port)
设定IP与端口
static void Connect()
建立连接
static void DisConnect()
断开连接
static void SendMessage(string messageType ,Dictionary<string,object> data)
发送消息
static void SendMessage(Dictionary<string, object> data)
发送消息,取出 data 中的'MT'(messageType)字段,作为messageType
数据以字符串格式传输,消息之间以‘&’符号结尾,如果消息中包含‘&’,则将其替换为“FCP:AND”,通过NetworkManager发送的Dictionary会被序列化成Json。
数据以二进制格式传输,编码格式类似Google Protocol Buffer,支持Int8,Int16以节约带宽,提供工具以生成Protocol文件,和数据解析类。
Tools -> Protocol -> C# to protocol c#类生成protocol文件
Tools -> Protocol -> protocol to c# 根据protocol文件生成c#类
Tools -> Protocol -> 生成解析代码 自动生成从消息变成消息类的解析代码
Tools -> Protocol -> 生成空解析文件 清除所有的生成代码,但是保留调用接口
Tools -> Protocol -> 清空文件夹 清除所有的生成文件
自动生成工具会获取到项目中所有CsharpProtocolInterface 和 IProtocolStructInterface 的子类,生成对应的protocol文件,
可以使用以下特性:
Int16Attribute 指定一个字段以16位Int传输
Int8Attribute 指定一个字段以8位Int传输
ModuleAttribute 声明某一个消息属于哪个模块,显式指定模块号
MessageModeAttribute 声明某一个消息是 ToClient 还是 ToServer
//建立连接
NetworkManager.Init<ProtocolNetworkService,SocketService>(System.Net.Sockets.ProtocolType.Tcp);
NetworkManager.SetServer(data.m_Address, data.m_port);
NetworkManager.Connect();
//发送消息
Dictionary<string, object> msg = new Dictionary<string, object>();
msg.Add("MT", "testMsg");
msg.Add("content", "hello");
NetworkManager.SendMessage(msg);
//接收消息
InputManager.AddListener<InputNetworkMessageEvent>(ReceviceMsg);
InputManager.RemoveListener<InputNetworkMessageEvent>(ReceviceMsg);
public void ReceviceMsg(InputNetworkMessageEvent msg)
{
Debug.Log(msg.m_MessgaeType);
Debug.Log(msg.Data["content"]);
}
//通过生成代码发送消息
PlayerLoginMsg_s msg = new PlayerLoginMsg_s();
msg.playerID = id;
msg.nickName = nickName;
ProtocolAnalysisService.SendCommand(msg);
//通过生成代码接收消息
ProtocolAnalysisService.Init(); //这一步必须要做
GlobalEvent.AddTypeEvent<PlayerLoginMsg_c>(ReceviceLoginMsg);
GlobalEvent.RemoveTypeEvent<PlayerLoginMsg_c>(ReceviceLoginMsg);
ProtocolAnalysisService.Dispose();
void ReceviceLoginMsg(PlayerLoginMsg_c e, params object[] obj)
{
Debug.Log("ReceviceLoginMsg");
}