From 905f7bb4cc2b167cbab692e11402ce750cb6db32 Mon Sep 17 00:00:00 2001 From: "DESKTOP-B25GA9E\\W35" <1733709035@qq.com> Date: Tue, 7 Mar 2023 16:45:06 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86udp=E5=9C=B0?= =?UTF-8?q?=E5=9D=80=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../UDPClient/Script/UDPClientModel.cs | 190 +++++++++++++----- .../UDPClient/Script/UDPClientView.cs | 63 +++--- .../UDPClient/Script/UDPUtility.cs | 142 ------------- .../UDPClient/Script/UDPUtility.cs.meta | 11 - README.md | 26 ++- 5 files changed, 191 insertions(+), 241 deletions(-) delete mode 100644 Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPUtility.cs delete mode 100644 Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPUtility.cs.meta diff --git a/Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPClientModel.cs b/Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPClientModel.cs index f3e357b..d304612 100644 --- a/Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPClientModel.cs +++ b/Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPClientModel.cs @@ -1,21 +1,20 @@ -using System.Collections; -using System.Collections.Generic; -using UnityEngine; +using UnityEngine; using QFrameworkCP; +using System; +using System.Text; +using System.Net.Sockets; +using System.Threading; +using System.Net; namespace JXSoft { public class UDPClientModel : DataEventModel { - private UDPLinkState udpState = UDPLinkState.NoIp; + private LinkStateDefault udpState = LinkStateDefault.Close; 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) { @@ -30,7 +29,7 @@ namespace JXSoft { public override void setLinkState(int linkStatus) { - this.udpState = (UDPLinkState)linkStatus; + this.udpState = (LinkStateDefault)linkStatus; this.SendEvent(new LinkStateChangedEvent(linkStatus)); } @@ -49,76 +48,157 @@ namespace JXSoft { this.udpPort = port; //此处可以加ip校验 Debug.LogWarning("此处未进行ip以及端口号校验,日后有需求可以增加"); - setLinkState((int)UDPLinkState.Linking); } - /// - /// 与服务端建立链接 - /// - public void linkServer() + public override bool Start() { - if (udpState == UDPLinkState.Linking) + bool isSuccess = this.GetUtility().StartUDPClient(udpAddress, udpPort); + if (udpState == LinkStateDefault.Close) { - if (!this.GetUtility().isOpenUDP) + if (isSuccess) { - - bool isSuccess = this.GetUtility().StartUDPClient(udpAddress, udpPort); - if (isSuccess) - { - setLinkState((int)UDPLinkState.LinkSucess); - } - else - { - setLinkState((int)UDPLinkState.LinkFaild); - } + setLinkState((int)LinkStateDefault.Open); + } + else + { + setLinkState((int)LinkStateDefault.Close); } } + return isSuccess; } - /// - /// 与服务端断开链接 - /// - public void closeServer() + public override bool Close() { - if (udpState == UDPLinkState.LinkSucess) + if (udpState == LinkStateDefault.Close) { if (this.GetUtility().isOpenUDP) { this.GetUtility().CloseUDPClient(); - setLinkState((int)UDPLinkState.NoIp); + setLinkState((int)LinkStateDefault.Close); } } + return true; } } - #region enum - public enum UDPLinkState + public class UDPUtility : IUtility { - NoIp = 0, - Linking = 1, - LinkFaild = 2, - LinkSucess = 3, - LinkTimeOut = 4 - } - #endregion + public string udpAddress; + public int udpPort; + public UdpClient udpClient; + public NetworkStream sendStream; + public bool isOpenUDP = false; + public bool isReceivedValue = false; + public string receivedData = ""; + public string exceptionData = ""; + public Thread reciveT; + public bool isTimeOut = false; + private IPEndPoint RemoteIpEndPoint; - #region event - public struct UDPStateChangedEvent - { - public UDPLinkState state; - public UDPStateChangedEvent(UDPLinkState state_) + public UDPUtility() { - state = state_; + Debug.LogWarning("使用无参数构造udp时,需要手动开启udp服务"); + } - } - public struct onUDPLinkException - { - public string exceptionMsg; - public onUDPLinkException(string exceptionMsg_) + public UDPUtility(string UDPAddress, int UDPPort) { - exceptionMsg = exceptionMsg_; + this.udpAddress = UDPAddress; + this.udpPort = UDPPort; + StartUDPClient(UDPAddress, UDPPort); + } + + public bool StartUDPClient(string ip, int port) + { + isTimeOut = false; + if (!isOpenUDP) + { + udpAddress = ip; + udpPort = port; + try + { + RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, udpPort); + udpClient = new UdpClient(RemoteIpEndPoint); + } + catch (Exception e) + { + exceptionData = e.ToString(); + return false; + } + isOpenUDP = true; + reciveT = new Thread(RecciveMsg); + reciveT.IsBackground = true; + reciveT.Start(); + return true; + } + return false; + } + + public void CloseUDPClient() + { + udpClient.Dispose(); + isOpenUDP = false; + reciveT.Abort(); + } + + public void sendData(string data) + { + if (isOpenUDP == false) + return; + Byte[] sendBytes = Encoding.Default.GetBytes(data); + udpClient.Send(sendBytes, sendBytes.Length); + } + public void sendData(string data, string ip, int port) + { + if (isOpenUDP == false) + return; + Byte[] sendBytes = Encoding.Default.GetBytes(data); + udpClient.Send(sendBytes, sendBytes.Length, ip, port); } - } - #endregion + public void RecciveMsg() + { + string msg = ""; + //Debug.Log("StartReceiving!"); + while (isOpenUDP) + { + try + { + Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); + msg = Encoding.UTF8.GetString(receiveBytes); + if (msg != "") + { + receivedData = msg; + isReceivedValue = true; + } + } + catch (Exception e) + { + isTimeOut = true; + exceptionData = e.ToString(); + } + } + Debug.Log("------------end While-------------"); + } + + /// + /// 线程接收到消息后 + /// + /// 接收到的消息 + public string getReceivedValue() + { + if (isReceivedValue) + { + isReceivedValue = false; + return receivedData; + } + else + { + return ""; + } + } + + public string getReceivedAddress() { + return RemoteIpEndPoint.Address.ToString() + ":" + RemoteIpEndPoint.Port.ToString(); + } + } } \ No newline at end of file diff --git a/Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPClientView.cs b/Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPClientView.cs index 39ca840..f5af82b 100644 --- a/Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPClientView.cs +++ b/Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPClientView.cs @@ -18,12 +18,6 @@ namespace JXSoft { } public class UDPClientView : MonoBehaviour, IController { - public UnityEvent onRecievedOpenDevice; - public UnityEvent onUDPLinkSuccess; - public UnityEvent onUDPLinkFaild; - public UnityEvent onServerConnected; - public UnityEvent onUDPReLink; - private string UDPAddress; private int UDPPort; private UDPUtility udpUtil; @@ -43,15 +37,9 @@ namespace JXSoft { if (udpUtil != null && !"".Equals(udpUtil.getReceivedValue())) { GameObject item = Instantiate(udpMsgItem, udpMsgContent); - item.GetComponentInChildren().text = udpUtil.receivedData; + item.GetComponentInChildren().text = udpUtil.receivedData + udpUtil.getReceivedAddress(); this.GetModel().onDataRecived.Invoke(udpUtil.receivedData); } - - if (udpUtil.getTimeOutState() && udpUtil.isOpenUDP) - { - this.SendEvent(new onUDPLinkException(udpUtil.exceptionData)); - udpUtil.isOpenUDP = false; - } } private void OnDestroy() { @@ -69,34 +57,20 @@ namespace JXSoft { { UDPAddress = "192.168.1.41"; UDPPort = 20000; - this.RegisterLinkStateEvent((int)UDPLinkState.Linking, () => { - Debug.Log("UDP开始链接"); - this.GetModel().linkServer(); - }); - this.RegisterLinkStateEvent((int)UDPLinkState.LinkSucess, () => - { - Debug.Log("UDP链接成功"); - onUDPLinkSuccess.Invoke(); - }); - this.RegisterLinkStateEvent((int)UDPLinkState.LinkFaild, () => - { - Debug.Log("UDP连接失败,请联系设备服务管理员"); - onUDPLinkFaild.Invoke(); - }); this.GetModel().setIP(UDPAddress, UDPPort); + this.GetModel().Start(); } public void restartUDPService() { - onUDPReLink.Invoke(); - this.GetModel().closeServer(); + this.GetModel().Close(); StartCoroutine(waitTwoSecond()); } public IEnumerator waitTwoSecond() { yield return new WaitForSeconds(2.0f); - this.GetModel().setLinkState((int)UDPLinkState.Linking); + this.GetModel().Start(); } public IArchitecture GetArchitecture() { @@ -104,4 +78,33 @@ namespace JXSoft { } } + public interface IUDPClient + { + + } + public static class UDPClientExtention + { + public static IUnRegister RegisterMessageEvent(this IUDPClient self, Action onEvent) where TResponse : IResponse + { + return UDPMangerArchitecture.Interface.RegisterEvent(e => { + if (e.res.GetType() == typeof(TResponse)) + { + onEvent.Invoke((TResponse)e.res); + } + }); + } + public static void onReceive(this IUDPClient self) where TResponse : IResponse, new() + { + UDPMangerArchitecture.Interface.GetModel().onReceive(); + } + public static void offReceive(this IUDPClient self) where TResponse : IResponse, new() + { + UDPMangerArchitecture.Interface.GetModel().offReceive(); + } + + public static void sendRequest(this IUDPClient self, TRequest request) where TRequest : IRequest, new() + { + UDPMangerArchitecture.Interface.GetModel().sendRequest(request); + } + } } \ No newline at end of file diff --git a/Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPUtility.cs b/Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPUtility.cs deleted file mode 100644 index 6fc9306..0000000 --- a/Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPUtility.cs +++ /dev/null @@ -1,142 +0,0 @@ -using UnityEngine; -using QFrameworkCP; -using System; -using System.Text; -using System.Net.Sockets; -using System.Threading; -using System.Net; - - -public class UDPUtility : IUtility -{ - public string udpAddress; - public int udpPort; - public UdpClient udpClient; - public NetworkStream sendStream; - public bool isOpenUDP = false; - public bool isReceivedValue = false; - public string receivedData = ""; - public string exceptionData = ""; - public Thread reciveT; - public bool isTimeOut = false; - private IPEndPoint RemoteIpEndPoint; - - public UDPUtility() - { - Debug.LogWarning("使用无参数构造udp时,需要手动开启udp服务"); - - } - public UDPUtility(string UDPAddress, int UDPPort) - { - this.udpAddress = UDPAddress; - this.udpPort = UDPPort; - StartUDPClient(UDPAddress, UDPPort); - } - - public bool StartUDPClient(string ip, int port) - { - isTimeOut = false; - if (!isOpenUDP) - { - udpAddress = ip; - udpPort = port; - try - { - RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, udpPort); - udpClient = new UdpClient(RemoteIpEndPoint); - } - catch (Exception e) - { - exceptionData = e.ToString(); - return false; - } - isOpenUDP = true; - reciveT = new Thread(RecciveMsg); - reciveT.IsBackground = true; - reciveT.Start(); - return true; - } - return false; - } - - public void CloseUDPClient() - { - udpClient.Dispose(); - isOpenUDP = false; - reciveT.Abort(); - } - - public void sendData(string data) - { - if (isOpenUDP == false) - return; - Byte[] sendBytes = Encoding.Default.GetBytes(data); - udpClient.Send(sendBytes, sendBytes.Length); - } - public void sendData(string data,string ip,int port) - { - if (isOpenUDP == false) - return; - Byte[] sendBytes = Encoding.Default.GetBytes(data); - udpClient.Send(sendBytes, sendBytes.Length,ip,port); - } - - public void RecciveMsg() - { - string msg = ""; - //Debug.Log("StartReceiving!"); - while (isOpenUDP) - { - try - { - Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); - msg = Encoding.UTF8.GetString(receiveBytes); - if (msg != "") - { - receivedData = msg; - isReceivedValue = true; - } - } - catch (Exception e) - { - Debug.LogWarning(e); - //断线发送异常 - isTimeOut = true; - exceptionData = e.ToString(); - break; - } - } - Debug.Log("------------end While-------------"); - } - - /// - /// 线程接收到消息后 - /// - /// 接收到的消息 - public string getReceivedValue() - { - if (isReceivedValue) - { - isReceivedValue = false; - return receivedData; - } - else - { - return ""; - } - } - - public bool getTimeOutState() - { - return isTimeOut; - } - - public bool IsReceivedMsg() - { - return sendStream.Length != 0; - } - public bool IsConnected() - { - return udpClient.Client.Connected; - } -} \ No newline at end of file diff --git a/Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPUtility.cs.meta b/Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPUtility.cs.meta deleted file mode 100644 index c4ba217..0000000 --- a/Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPUtility.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 4b85b7b0fa7d90c47931dfa186fbe3e4 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/README.md b/README.md index e3584d4..c534ac9 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ JXsoft是由github作者jkpete编写的一款基于Qframework实现的Unity信 该项目使用了QFramework作为框架基础依赖,该套件也可以脱离QFramework单独使用。 -QFramework链接:[GitHub - liangxiegame/QFramework: Unity3D System Design Architecture](https://github.com/liangxiegame/QFramework) +[QFramework链接](https://github.com/liangxiegame/QFramework) 最近更新:增加了HttpServer,可以使用Unity搭建Http服务器了。 @@ -17,13 +17,33 @@ QFramework链接:[GitHub - liangxiegame/QFramework: Unity3D System Design Arch 目前支持的通讯方式一览,后续会增加更多的通讯方式 | Client | Server | -| ------ | ------ | +|:------ | ------ | | TCP | TCP | -| UDP | UDP | +| UDP | | | | Http | 对应的接口命名为 I + Name + Type (e.g. ITCPClient,ITCPServer) +UDP虽然是无连接协议,但通讯包是基于UDPClient这个类编写的,故归为Client那一栏 + +详情参考 [UdpClient 类官方说明](https://learn.microsoft.com/zh-cn/dotnet/api/system.net.sockets.udpclient?view=netframework-4.8) + + + +目前支持的协议格式一览,后续会增加更多协议格式转换 + +| Protocol | +| -------- | +| Hex | +| Json | +| String | + +协议转换方案后续由协议API提供参考跟封装(此处用了litjson作为协议转换方案)。 + + + + + # 使用方法 ## 1.定义响应&请求消息结构