using System.Collections; using System.Collections.Generic; using UnityEngine; using QFramework; 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 => { setUDPState(UDPLinkState.LinkTimeOut); this.GetUtility().CloseUDPClient(); }); this.RegisterEvent(e => { if (this.GetUtility().isOpenUDP) { this.GetUtility().sendData(e.req.toJson()); } else { Debug.LogWarning("请先开启UDP链接"); } }); } public void setUDPState(UDPLinkState state) { this.udpState = state; this.SendEvent(new UDPStateChangedEvent(state)); } public UDPLinkState getState() { return this.udpState; } /// /// 设置对应IP,设置完毕后,自动进入链接状态(此时需要用户手动监听是否要进行链接服务器) /// /// ip地址 /// 端口号 public void setIP(string ip, int port) { this.udpAddress = ip; this.udpPort = port; //此处可以加ip校验 Debug.LogWarning("此处未进行ip以及端口号校验,日后有需求可以增加"); setUDPState(UDPLinkState.Linking); } /// /// 与服务端建立链接 /// public void linkServer() { if (udpState == UDPLinkState.Linking) { if (!this.GetUtility().isOpenUDP) { bool isSuccess = this.GetUtility().StartUDPClient(udpAddress, udpPort); if (isSuccess) { setUDPState(UDPLinkState.LinkSucess); } else { setUDPState(UDPLinkState.LinkFaild); } } } } /// /// 与服务端断开链接 /// public void closeServer() { if (udpState == UDPLinkState.LinkSucess) { if (this.GetUtility().isOpenUDP) { this.GetUtility().CloseUDPClient(); setUDPState(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