using System.Collections; using System.Collections.Generic; using UnityEngine; using QFrameworkCP; namespace JXSoft { public class UDPEventModel : DataEventModel { private UDPLinkState udpState = UDPLinkState.NoIp; private string udpAddress = ""; private int udpPort = 0; public string myAddress = ""; protected override void OnInit() { this.RegisterEvent(e => { setLinkState((int)UDPLinkState.LinkTimeOut); this.GetUtility().CloseUDPClient(); }); this.RegisterEvent(e => { if (this.GetUtility().isOpenUDP) { this.GetUtility().sendData(e.req.toProtocolData()); } else { Debug.LogWarning("请先开启UDP链接"); } }); } public override void setLinkState(int linkStatus) { this.udpState = (UDPLinkState)linkStatus; this.SendEvent(new LinkStateChangedEvent(linkStatus)); } public override int getLinkState() { return (int)this.udpState; } /// /// 设置对应IP,设置完毕后,自动进入链接状态(此时需要用户手动监听是否要进行链接服务器) /// /// ip地址 /// 端口号 public void setIP(string ip, int port) { this.udpAddress = ip; this.udpPort = port; //此处可以加ip校验 Debug.LogWarning("此处未进行ip以及端口号校验,日后有需求可以增加"); setLinkState((int)UDPLinkState.Linking); } /// /// 与服务端建立链接 /// public void linkServer() { if (udpState == UDPLinkState.Linking) { if (!this.GetUtility().isOpenUDP) { bool isSuccess = this.GetUtility().StartUDPClient(udpAddress, udpPort); if (isSuccess) { setLinkState((int)UDPLinkState.LinkSucess); } else { setLinkState((int)UDPLinkState.LinkFaild); } } } } /// /// 与服务端断开链接 /// public void closeServer() { if (udpState == UDPLinkState.LinkSucess) { if (this.GetUtility().isOpenUDP) { this.GetUtility().CloseUDPClient(); setLinkState((int)UDPLinkState.NoIp); } } } } #region enum public enum UDPLinkState { NoIp = 0, Linking = 1, LinkFaild = 2, LinkSucess = 3, LinkTimeOut = 4 } #endregion #region event public struct UDPStateChangedEvent { public UDPLinkState state; public UDPStateChangedEvent(UDPLinkState state_) { state = state_; } } public struct onUDPLinkException { public string exceptionMsg; public onUDPLinkException(string exceptionMsg_) { exceptionMsg = exceptionMsg_; } } #endregion }