Browse Source

添加了udp地址输出

master
DESKTOP-B25GA9E\W35 2 years ago
parent
commit
905f7bb4cc
  1. 190
      Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPClientModel.cs
  2. 63
      Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPClientView.cs
  3. 142
      Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPUtility.cs
  4. 11
      Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPUtility.cs.meta
  5. 26
      README.md

190
Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPClientModel.cs

@ -1,21 +1,20 @@
using System.Collections; using UnityEngine;
using System.Collections.Generic;
using UnityEngine;
using QFrameworkCP; using QFrameworkCP;
using System;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
namespace JXSoft { namespace JXSoft {
public class UDPClientModel : DataEventModel public class UDPClientModel : DataEventModel
{ {
private UDPLinkState udpState = UDPLinkState.NoIp; private LinkStateDefault udpState = LinkStateDefault.Close;
private string udpAddress = ""; private string udpAddress = "";
private int udpPort = 0; private int udpPort = 0;
public string myAddress = ""; public string myAddress = "";
protected override void OnInit() protected override void OnInit()
{ {
this.RegisterEvent<onUDPLinkException>(e => {
setLinkState((int)UDPLinkState.LinkTimeOut);
this.GetUtility<UDPUtility>().CloseUDPClient();
});
this.RegisterEvent<RequestMsgEvent>(e => { this.RegisterEvent<RequestMsgEvent>(e => {
if (this.GetUtility<UDPUtility>().isOpenUDP) if (this.GetUtility<UDPUtility>().isOpenUDP)
{ {
@ -30,7 +29,7 @@ namespace JXSoft {
public override void setLinkState(int linkStatus) public override void setLinkState(int linkStatus)
{ {
this.udpState = (UDPLinkState)linkStatus; this.udpState = (LinkStateDefault)linkStatus;
this.SendEvent(new LinkStateChangedEvent(linkStatus)); this.SendEvent(new LinkStateChangedEvent(linkStatus));
} }
@ -49,76 +48,157 @@ namespace JXSoft {
this.udpPort = port; this.udpPort = port;
//此处可以加ip校验 //此处可以加ip校验
Debug.LogWarning("此处未进行ip以及端口号校验,日后有需求可以增加"); Debug.LogWarning("此处未进行ip以及端口号校验,日后有需求可以增加");
setLinkState((int)UDPLinkState.Linking);
} }
/// <summary> public override bool Start()
/// 与服务端建立链接
/// </summary>
public void linkServer()
{ {
if (udpState == UDPLinkState.Linking) bool isSuccess = this.GetUtility<UDPUtility>().StartUDPClient(udpAddress, udpPort);
if (udpState == LinkStateDefault.Close)
{ {
if (!this.GetUtility<UDPUtility>().isOpenUDP) if (isSuccess)
{ {
setLinkState((int)LinkStateDefault.Open);
bool isSuccess = this.GetUtility<UDPUtility>().StartUDPClient(udpAddress, udpPort); }
if (isSuccess) else
{ {
setLinkState((int)UDPLinkState.LinkSucess); setLinkState((int)LinkStateDefault.Close);
}
else
{
setLinkState((int)UDPLinkState.LinkFaild);
}
} }
} }
return isSuccess;
} }
/// <summary> public override bool Close()
/// 与服务端断开链接
/// </summary>
public void closeServer()
{ {
if (udpState == UDPLinkState.LinkSucess) if (udpState == LinkStateDefault.Close)
{ {
if (this.GetUtility<UDPUtility>().isOpenUDP) if (this.GetUtility<UDPUtility>().isOpenUDP)
{ {
this.GetUtility<UDPUtility>().CloseUDPClient(); this.GetUtility<UDPUtility>().CloseUDPClient();
setLinkState((int)UDPLinkState.NoIp); setLinkState((int)LinkStateDefault.Close);
} }
} }
return true;
} }
} }
#region enum public class UDPUtility : IUtility
public enum UDPLinkState
{ {
NoIp = 0, public string udpAddress;
Linking = 1, public int udpPort;
LinkFaild = 2, public UdpClient udpClient;
LinkSucess = 3, public NetworkStream sendStream;
LinkTimeOut = 4 public bool isOpenUDP = false;
} public bool isReceivedValue = false;
#endregion public string receivedData = "";
public string exceptionData = "";
public Thread reciveT;
public bool isTimeOut = false;
private IPEndPoint RemoteIpEndPoint;
#region event public UDPUtility()
public struct UDPStateChangedEvent
{
public UDPLinkState state;
public UDPStateChangedEvent(UDPLinkState state_)
{ {
state = state_; Debug.LogWarning("使用无参数构造udp时,需要手动开启udp服务");
} }
} public UDPUtility(string UDPAddress, int UDPPort)
public struct onUDPLinkException
{
public string exceptionMsg;
public onUDPLinkException(string exceptionMsg_)
{ {
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-------------");
}
/// <summary>
/// 线程接收到消息后
/// </summary>
/// <returns>接收到的消息</returns>
public string getReceivedValue()
{
if (isReceivedValue)
{
isReceivedValue = false;
return receivedData;
}
else
{
return "";
}
}
public string getReceivedAddress() {
return RemoteIpEndPoint.Address.ToString() + ":" + RemoteIpEndPoint.Port.ToString();
}
}
} }

63
Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPClientView.cs

@ -18,12 +18,6 @@ namespace JXSoft {
} }
public class UDPClientView : MonoBehaviour, IController public class UDPClientView : MonoBehaviour, IController
{ {
public UnityEvent onRecievedOpenDevice;
public UnityEvent onUDPLinkSuccess;
public UnityEvent onUDPLinkFaild;
public UnityEvent onServerConnected;
public UnityEvent onUDPReLink;
private string UDPAddress; private string UDPAddress;
private int UDPPort; private int UDPPort;
private UDPUtility udpUtil; private UDPUtility udpUtil;
@ -43,15 +37,9 @@ namespace JXSoft {
if (udpUtil != null && !"".Equals(udpUtil.getReceivedValue())) if (udpUtil != null && !"".Equals(udpUtil.getReceivedValue()))
{ {
GameObject item = Instantiate(udpMsgItem, udpMsgContent); GameObject item = Instantiate(udpMsgItem, udpMsgContent);
item.GetComponentInChildren<Text>().text = udpUtil.receivedData; item.GetComponentInChildren<Text>().text = udpUtil.receivedData + udpUtil.getReceivedAddress();
this.GetModel<UDPClientModel>().onDataRecived.Invoke(udpUtil.receivedData); this.GetModel<UDPClientModel>().onDataRecived.Invoke(udpUtil.receivedData);
} }
if (udpUtil.getTimeOutState() && udpUtil.isOpenUDP)
{
this.SendEvent(new onUDPLinkException(udpUtil.exceptionData));
udpUtil.isOpenUDP = false;
}
} }
private void OnDestroy() private void OnDestroy()
{ {
@ -69,34 +57,20 @@ namespace JXSoft {
{ {
UDPAddress = "192.168.1.41"; UDPAddress = "192.168.1.41";
UDPPort = 20000; UDPPort = 20000;
this.RegisterLinkStateEvent((int)UDPLinkState.Linking, () => {
Debug.Log("UDP开始链接");
this.GetModel<UDPClientModel>().linkServer();
});
this.RegisterLinkStateEvent((int)UDPLinkState.LinkSucess, () =>
{
Debug.Log("UDP链接成功");
onUDPLinkSuccess.Invoke();
});
this.RegisterLinkStateEvent((int)UDPLinkState.LinkFaild, () =>
{
Debug.Log("UDP连接失败,请联系设备服务管理员");
onUDPLinkFaild.Invoke();
});
this.GetModel<UDPClientModel>().setIP(UDPAddress, UDPPort); this.GetModel<UDPClientModel>().setIP(UDPAddress, UDPPort);
this.GetModel<UDPClientModel>().Start();
} }
public void restartUDPService() public void restartUDPService()
{ {
onUDPReLink.Invoke(); this.GetModel<UDPClientModel>().Close();
this.GetModel<UDPClientModel>().closeServer();
StartCoroutine(waitTwoSecond()); StartCoroutine(waitTwoSecond());
} }
public IEnumerator waitTwoSecond() public IEnumerator waitTwoSecond()
{ {
yield return new WaitForSeconds(2.0f); yield return new WaitForSeconds(2.0f);
this.GetModel<UDPClientModel>().setLinkState((int)UDPLinkState.Linking); this.GetModel<UDPClientModel>().Start();
} }
public IArchitecture GetArchitecture() public IArchitecture GetArchitecture()
{ {
@ -104,4 +78,33 @@ namespace JXSoft {
} }
} }
public interface IUDPClient
{
}
public static class UDPClientExtention
{
public static IUnRegister RegisterMessageEvent<TResponse>(this IUDPClient self, Action<TResponse> onEvent) where TResponse : IResponse
{
return UDPMangerArchitecture.Interface.RegisterEvent<ResponseMsgEvent>(e => {
if (e.res.GetType() == typeof(TResponse))
{
onEvent.Invoke((TResponse)e.res);
}
});
}
public static void onReceive<TResponse>(this IUDPClient self) where TResponse : IResponse, new()
{
UDPMangerArchitecture.Interface.GetModel<UDPClientModel>().onReceive<TResponse>();
}
public static void offReceive<TResponse>(this IUDPClient self) where TResponse : IResponse, new()
{
UDPMangerArchitecture.Interface.GetModel<UDPClientModel>().offReceive<TResponse>();
}
public static void sendRequest<TRequest>(this IUDPClient self, TRequest request) where TRequest : IRequest, new()
{
UDPMangerArchitecture.Interface.GetModel<UDPClientModel>().sendRequest(request);
}
}
} }

142
Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPUtility.cs

@ -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-------------");
}
/// <summary>
/// 线程接收到消息后
/// </summary>
/// <returns>接收到的消息</returns>
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;
}
}

11
Assets/MsgTransmitTools/ExtendLinkModel/UDPClient/Script/UDPUtility.cs.meta

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 4b85b7b0fa7d90c47931dfa186fbe3e4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

26
README.md

@ -8,7 +8,7 @@ JXsoft是由github作者jkpete编写的一款基于Qframework实现的Unity信
该项目使用了QFramework作为框架基础依赖,该套件也可以脱离QFramework单独使用。 该项目使用了QFramework作为框架基础依赖,该套件也可以脱离QFramework单独使用。
QFramework链接:[GitHub - liangxiegame/QFramework: Unity3D System Design Architecture](https://github.com/liangxiegame/QFramework) [QFramework链接](https://github.com/liangxiegame/QFramework)
最近更新:增加了HttpServer,可以使用Unity搭建Http服务器了。 最近更新:增加了HttpServer,可以使用Unity搭建Http服务器了。
@ -17,13 +17,33 @@ QFramework链接:[GitHub - liangxiegame/QFramework: Unity3D System Design Arch
目前支持的通讯方式一览,后续会增加更多的通讯方式 目前支持的通讯方式一览,后续会增加更多的通讯方式
| Client | Server | | Client | Server |
| ------ | ------ | |:------ | ------ |
| TCP | TCP | | TCP | TCP |
| UDP | UDP | | UDP | |
| | Http | | | Http |
对应的接口命名为 I + Name + Type (e.g. ITCPClient,ITCPServer) 对应的接口命名为 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.定义响应&请求消息结构 ## 1.定义响应&请求消息结构

Loading…
Cancel
Save