using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using QFrameworkCP; using JXSoft; using System; namespace JXSoft { public class TCPMangerArchitecture : Architecture { protected override void Init() { this.RegisterUtility(new TCPUtility()); this.RegisterModel(new TCPEventModel()); } } public class TCPClientView : MonoBehaviour,IController,ICanRegisterEvent { public UnityEvent onRecievedOpenDevice; public UnityEvent onTCPLinkSuccess; public UnityEvent onTCPLinkFaild; public UnityEvent onServerConnected; public UnityEvent onTCPReLink; private string tcpAddress; private int tcpPort; private int deviceId; // Start is called before the first frame update void Awake() { initTCPService(); DontDestroyOnLoad(this); } public void initTCPService() { tcpAddress = "127.0.0.1"; tcpPort = 20000; deviceId = 1; this.RegisterEvent(e => { if (e.linkState == (int)TCPLinkState.Linking) { Debug.Log("TCP开始链接"); this.GetModel().linkServer(); } if (e.linkState == (int)TCPLinkState.LinkSucess) { Debug.Log("TCP链接成功"); this.GetModel().onReceive(); this.GetModel().sendRequestCommand(new LinkTCPRequest(deviceId)); onTCPLinkSuccess.Invoke(); } if (e.linkState == (int)TCPLinkState.LinkFaild) { Debug.Log("TCP连接失败,请联系设备服务管理员"); onTCPLinkFaild.Invoke(); } }); this.RegisterEvent(e => { if (e.res.GetType() == typeof(LinkSuccessResponse)) { Debug.Log("Link Server success"); this.GetModel().offReceive(); onServerConnected.Invoke(); } }); this.GetModel().setLinkState((int)TCPLinkState.NoIp); this.GetModel().setIP(tcpAddress, tcpPort); } public void restartTCPService() { onTCPReLink.Invoke(); this.GetModel().closeServer(); StartCoroutine(waitTwoSecond()); } public IEnumerator waitTwoSecond() { yield return new WaitForSeconds(2.0f); this.GetModel().setLinkState((int)TCPLinkState.Linking); } public IArchitecture GetArchitecture() { return TCPMangerArchitecture.Interface; } } public class LinkSuccessResponse : AbstractResponse { public string code; public string data; public string msg; public LinkSuccessResponse() { this.code = ""; this.data = ""; this.msg = ""; } } public class LinkTCPRequest :IRequest{ public string id; public int type; public LinkTCPRequest(int id) { this.id = id.ToString(); this.type = 1; } public string toJson() { return JsonUtility.ToJson(this); } } }