Udp连接也是基于GameBox,在初始化时创建一个Udp通信:
public UdpConnection()
{
GameWorld.Instance.OnApplicationQuit(Disconnect);
new ServiceTask(new[]
{
typeof(IByteStorage),
typeof(INetworkManager)
}).Start().Continue(t =>
{
_iNetworkManager = ServiceCenter.GetService<INetworkManager>();
return null;
});
}
public void Init()
{
_iSocketChannel = _iNetworkManager.Create("udp") as ISocketChannel;
_iSocketChannel.Setup(this);
_iSocketChannel.OnChannelStateChange = OnServerStateChange;
}
由于Udp协议会产生丢包乱序等现象,需要在接收udp消息时过滤掉旧消息包(可以通过消息包编号)
继承接口IProtocolHost处理消息收发:
public void Pack(IObjectReader reader, IByteArray writer)
{
var message = reader.ReadOne() as SendPackage;
var byteArray = Pack(message);
writer.WriteBytes(byteArray.Bytes, 0, byteArray.Length);
}
public void Unpack(IByteArray reader, IObjectWriter writer)
{
_receiveArray.WriteBytes(reader.ReadBytes());
Unpack();
#if HShowSocket
Service.UIManager.MoveSocketStr = "当前通信协议:udp";
#endif
}