using System.Collections; using System.Collections.Generic; using UnityEngine; using QFramework; namespace TCPClientTools { //统筹管理TCP的命令池以及相关链接信息 public class TCPEventModel : DataEventModel, ICanSendCommand,ICanRegisterEvent { private TCPLinkState tcpState = TCPLinkState.NoIp; private string tcpAddress = ""; private int tcpPort = 0; public string myAddress = ""; protected override void OnInit() { myAddress = this.GetUtility().GetIP(); this.RegisterEvent(e=> { setTCPState(TCPLinkState.LinkTimeOut); this.GetUtility().CloseTCPClient(); }); //注册重写发送事件 this.RegisterEvent(e => { if (this.GetUtility().isOpenTCP) { this.GetUtility().sendData(e.req.toJson()); } else { Debug.LogWarning("请先开启TCP链接"); } }); } public void setTCPState(TCPLinkState state) { this.tcpState = state; this.SendEvent(new TCPStateChangedEvent(state)); } public TCPLinkState getState() { return this.tcpState; } /// /// 设置对应IP,设置完毕后,自动进入链接状态(此时需要用户手动监听是否要进行链接服务器) /// /// ip地址 /// 端口号 public void setIP(string ip,int port) { this.tcpAddress = ip; this.tcpPort = port; //此处可以加ip校验 Debug.LogWarning("此处未进行ip以及端口号校验,日后有需求可以增加"); setTCPState(TCPLinkState.Linking); } /// /// 与服务端建立链接 /// public void linkServer() { if (tcpState == TCPLinkState.Linking) { if (!this.GetUtility().isOpenTCP) { bool isSuccess = this.GetUtility().StartTCPClient(tcpAddress, tcpPort); if (isSuccess) { setTCPState(TCPLinkState.LinkSucess); } else { setTCPState(TCPLinkState.LinkFaild); } } } } /// /// 与服务端断开链接 /// public void closeServer() { if (tcpState == TCPLinkState.LinkSucess) { if (this.GetUtility().isOpenTCP) { this.GetUtility().CloseTCPClient(); setTCPState(TCPLinkState.NoIp); } } } } #region enum public enum TCPLinkState { NoIp = 0, Linking = 1, LinkFaild = 2, LinkSucess = 3, LinkTimeOut = 4 } #endregion #region event public struct TCPStateChangedEvent { public TCPLinkState state; public TCPStateChangedEvent(TCPLinkState state_) { state = state_; } } public struct onLinkException { public string exceptionMsg; public onLinkException(string exceptionMsg_) { exceptionMsg = exceptionMsg_; } } #endregion }