This commit is contained in:
陈向学 2024-02-27 15:33:01 +08:00
parent e29060cbfe
commit 1f491565a4
17 changed files with 749 additions and 6 deletions

8
Assets/Editor.meta Normal file
View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 9545db1eb965bdd43bc46c5ec1e51840
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,19 @@
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(DisplayOnly))]
public class ReadOnlyDrawer : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return EditorGUI.GetPropertyHeight(property, label, true);
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
GUI.enabled = false;
EditorGUI.PropertyField(position, property, label, true);
GUI.enabled = true;
}
}

View File

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

View File

@ -1 +1 @@
127.0.0.1:48888
172.16.1.254:48888

View File

@ -0,0 +1 @@
serverIP=172.16.1.154

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 286a995b4682ee24e898f1a251081a8e
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -225,6 +225,7 @@ GameObject:
- component: {fileID: 2132962759}
- component: {fileID: 2132962760}
- component: {fileID: 2132962758}
- component: {fileID: 2132962761}
m_Layer: 0
m_Name: Net
m_TagString: Untagged
@ -274,3 +275,17 @@ MonoBehaviour:
m_Script: {fileID: 11500000, guid: 7849c2de1b8e12e478bd7b1e0af1e553, type: 3}
m_Name:
m_EditorClassIdentifier:
--- !u!114 &2132962761
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2132962757}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 8f4de7d1cb6612d42ba96f515d29e3d5, type: 3}
m_Name:
m_EditorClassIdentifier:
PubIP: 127.0.0.1:8082
SubIP: 127.0.0.1:8081

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 94b32ba3a20dc8443b0e53007662dbc8
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,261 @@
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Linq;
using System.Collections;
using System.IO;
using Newtonsoft.Json.Linq;
public class LoadManage : MonoBehaviour
{
public static LoadManage Instance;
/// <summary>
/// 房间域 "Room"
/// </summary>
[DisplayOnly]
public string currentRoomArea;
/// <summary>
/// 训练状态
/// </summary>
public static ProgramState programState = ProgramState.;
/// <summary>
/// 是否暂停
/// </summary>
public static bool isPause;
/// <summary>
/// 与RoomServer通信
/// </summary>
[DisplayOnly]
public MyNetMQClient RSclient;
public static Action<string> registRequset;
public static Action<string> getusersRequset;
public static Action<string> createRoomRequset;
public static Action<string> getRoomsRequset;
public static Action<string> getownRoomsRequset;
public static Action<string> joinRoomRequset;
public static Action<string> joinsRequset;
public static Action<string> leaveRoomRequset;
public static Action<string> closeRoomRequset;
public static Action<ulong, string, string> playerInfoRequset;
public static Action<string> getroomusersRequset;
public static Action<string> send2roomRequset;
public static Action<string> send2userRequset;
public static Action<string> send2worldRequset;
private void Awake()
{
Instance = this;
DontDestroyOnLoad(gameObject);
#if UNITY_EDITOR
UnityEngine.Debug.unityLogger.logEnabled = true;
#else
UnityEngine.Debug.unityLogger.logEnabled = false;
#endif
}
void Start()
{
//设置不休眠
Screen.sleepTimeout = SleepTimeout.NeverSleep;
string ip = "";
//配置
File.ReadAllLines(Application.streamingAssetsPath + "/MainSetting.txt").ToList().ForEach(line =>
{
if(line.Trim(' ').StartsWith("serverIP="))
{
string[] tmps = line.Trim(' ').Split('=');
ip= tmps[1];
}
});
CreateRoomServerClient(string.Format("tcp://{0}:8889",ip), string.Format("tcp://{0}:8888",ip));
MyNetMQClient.instance._netMqListener.SubTopic("Room");
SceneManager.LoadScene("SampleScene");
}
/// <summary>
/// 创建与roomServer通信的客户端
/// </summary>
public void CreateRoomServerClient(string roomServerSubIP, string roomServerPubIP)
{
if (RSclient == null)
{
//测试
//roomServerPubIP = "tcp://192.168.1.125:56987";
// roomServerSubIP = "tcp://192.168.1.125:56991";
RSclient = gameObject.AddComponent<MyNetMQClient>();
RSclient.Init(roomServerPubIP, roomServerSubIP, ReciveFromRoomServerInThread, ReciveFromRoomServerInMono, "roomServer");
Debug.Log("开启roomServer:" + roomServerPubIP + "------" + roomServerSubIP);
}
}
public void RemoveRoomServerClient()
{
if (RSclient != null)
{
RSclient.Destroy();
// RSclient = null;
Debug.Log("RSclient置空");
}
}
/// <summary>
/// RoomServermono
/// </summary>
/// <param name="stS"></param>
private void ReciveFromRoomServerInThread(st_Motions stS)
{
if (stS.area == "Room")
{
//同步消息
//if (programState == ProgramState.进行中)
//{
// if (stS.m_iOperaType == 10006)
// {
// //单值同步
// int syncid = BitConverter.ToInt32(stS.m_sOperaData, 0);
// if (LoadManage.Instance.me.SyncId != syncid)
// {
// int legth = BitConverter.ToInt32(stS.m_sOperaData, 4);
// string id = Encoding.UTF8.GetString(stS.m_sOperaData, 8, legth);
// if (OneValueSyncObject.OneAxisSyncObjectList.ContainsKey(id))
// {
// if (stS.m_sOperaData[9 + legth] == 0)
// {
// //无回调
// OneValueSyncObject.OneAxisSyncObjectList[id].SetValue(8 + legth, stS.m_sOperaData);
// }
// else
// {
// //有回调
// RSclient._netMqListener.AddToMono(stS);
// }
// }
// }
// }
// else if (stS.m_iOperaType == 10007)
// {
// //坐标角度同步
// int syncid = BitConverter.ToInt32(stS.m_sOperaData, 0);
// if (LoadManage.Instance.me.SyncId != syncid)
// {
// int legth = BitConverter.ToInt32(stS.m_sOperaData, 4);
// string id = Encoding.UTF8.GetString(stS.m_sOperaData, 8, legth);
// if (FunctionSync_PositionRoate.positionRoateSyncObejctList.ContainsKey(id))
// {
// FunctionSync_PositionRoate.positionRoateSyncObejctList[id].SetValue(8 + legth, stS.m_sOperaData);
// }
// }
// }
// else if (stS.m_iOperaType == 61)
// {
// //心跳检测
// //XinTiaoCheck();
// }
// else
// {
// RSclient._netMqListener.AddToMono(stS);
// }
//}
}
else if(stS.area == "System")
{
//系统消息
RSclient._netMqListener.AddToMono(stS);
}
}
/// <summary>
/// RoomServermono
/// </summary>
/// <param name="data"></param>
public void ReciveFromRoomServerInMono(st_Motions stS)
{
#if !UNITY_EDITOR
try
{
#endif
string message = Encoding.UTF8.GetString(stS.m_sOperaData);
string[] commands = message.Split(' ');
if (commands.Length > 0)
{
//Debug.Log($"<color=green>commands[0]===={commands[0]}</color>");
switch (commands[0])
{
case "regist":
registRequset?.Invoke(commands[1]);
break;
case "getusers":
getusersRequset?.Invoke(commands[1]);
break;
case "createroom":
createRoomRequset?.Invoke(commands[1]);
break;
case "getrooms":
getRoomsRequset?.Invoke(commands[1]);
break;
case "getownrooms":
getownRoomsRequset?.Invoke(commands[1]);
break;
case "joinroom":
joinRoomRequset?.Invoke(commands[1]);
break;
case "joins":
joinsRequset?.Invoke(commands[1]);
break;
case "leaveroom":
leaveRoomRequset?.Invoke(commands[1]);
break;
case "closeroom":
closeRoomRequset?.Invoke(commands[1]);
break;
case "player":
string[] data = commands[1].Split(';');
if (data.Length == 3)
{
playerInfoRequset?.Invoke(ulong.Parse(data[0]), data[1], data[2]);
}
break;
case "getroomusers":
getroomusersRequset?.Invoke(commands[1]);
break;
case "send2room":
send2roomRequset?.Invoke(commands[1]);
break;
case "send2user":
send2userRequset?.Invoke(commands[1]);
break;
case "send2world":
send2worldRequset?.Invoke(commands[1]);
break;
}
}
#if !UNITY_EDITOR
}
catch (Exception e)
{
Debug.LogError(e.Message);
}
#endif
}
private void OnDestroy()
{
Debug.Log("OnDestroy");
if (RSclient != null)
{
RSclient.Destroy();
}
}
}

View File

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

View File

@ -0,0 +1,119 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Diagnostics;
using UnityEngine.Networking;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class MyNetMQClient : MonoBehaviour
{
public static MyNetMQClient instance;
[DisplayOnly]
public string PubIP= "127.0.0.1:8082";
[DisplayOnly]
public string SubIP = "127.0.0.1:8081";
/// <summary>
/// 接口IP (配置文件)
/// </summary>
public static string CallIP = "192.168.1.161:8080";
public static string SyncServerIP = "192.168.1.161:8888";
public static string remoteServerIP = "192.168.1.161:8890";
[HideInInspector]
public NetMqListener _netMqListener;
[HideInInspector]
public NetMqPublisher _netMqPublisher;
private void Awake()
{
instance = this;
}
/// <summary>
/// 初始化Netmq
/// </summary>
/// <param name="reciveInMono">接收函数</param>
public void Init(string ServerSubIP,string ServerPubIP, NetMqListener.ReciveMessageInThread reciveInthread, NetMqListener.ReceiceMessageInMono reciveInMono,string typename)
{
SubIP = ServerSubIP;
PubIP = ServerPubIP;
//开启接收模块
_netMqListener = new NetMqListener(ServerSubIP, reciveInthread, reciveInMono);
_netMqListener.typeName = typename;
//开启发送模块
_netMqPublisher = new NetMqPublisher(ServerPubIP);
_netMqPublisher.typeName = typename;
}
public void Send(string area,int type,byte[] data)
{
_netMqPublisher.AddMessageToSendQue(area, type, data);
}
public void Send(st_Motions st)
{
_netMqPublisher.AddMessageToSendQue(st);
}
private void Update()
{
if (_netMqListener != null)
{
_netMqListener.UpdateByte();
}
}
public void Destroy()
{
_netMqListener._listenerCancelled = true;
_netMqPublisher._listenerCancelled = true;
UnityEngine.Debug.Log("销毁xxxxx");
Destroy(this);
}
}
/// <summary>
/// 消息体
/// </summary>
[Serializable]
public class st_Motions
{
/// <summary>
/// 域
/// </summary>
public string area;
/// <summary>
/// 消息标识
/// </summary>
public int m_iOperaType;
/// <summary>
/// 消息内容byte[256]
/// </summary>
public byte[] m_sOperaData;
}
/// <summary>
/// 演习状态
/// </summary>
public enum ProgramState
{
,
}
public class DisplayOnly : PropertyAttribute
{
}

View File

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

View File

@ -0,0 +1,148 @@
using NetMQ;
using NetMQ.Sockets;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using UnityEngine;
/// <summary>
/// 订阅模块
/// </summary>
public class NetMqListener
{
private string serverSubIP;
private Thread _listenerWorker;
public bool _listenerCancelled;
/// <summary>
/// 自定义名称
/// </summary>
public string typeName;
/// <summary>
/// 处理函数委托
/// </summary>
/// <param name="st"></param>
public delegate void ReceiceMessageInMono(st_Motions st);
public delegate void ReciveMessageInThread(st_Motions st);
/// <summary>
/// mono里处理消息
/// </summary>
private readonly ReceiceMessageInMono _reciveMessageInMono;
/// <summary>
/// 线程里处理模型
/// </summary>
private readonly ReciveMessageInThread _reciveMessageInThread;
private readonly List<st_Motions> _messageReciveStmotion = new List<st_Motions>();
/// <summary>
/// 注册委托函数
/// </summary>
public NetMqListener(string subIP , ReciveMessageInThread _reciveInThread, ReceiceMessageInMono reciveInMono)
{
serverSubIP = subIP;
_reciveMessageInThread += _reciveInThread;
_reciveMessageInMono += reciveInMono;
StartListen();
}
/// <summary>
/// 开始监听
/// </summary>
public void StartListen()
{
_listenerCancelled = false;
_listenerWorker = new Thread(ByteListenerWork);
_listenerWorker.IsBackground = true;
_listenerWorker.Start();
}
/// <summary>
/// 停止监听
/// </summary>
public void StopListen()
{
_listenerCancelled = true;
//_listenerWorker.Join();
}
public SubscriberSocket subSocket;
/// <summary>
/// 接收线程
/// </summary>
private void ByteListenerWork()
{
AsyncIO.ForceDotNet.Force();
using (subSocket = new SubscriberSocket())
{
subSocket.Options.ReceiveHighWatermark = 1000;
subSocket.Connect(serverSubIP);
UnityEngine.Debug.Log("客户端开启成功:" + serverSubIP);
while (!_listenerCancelled)
{
//try
//{
List<byte[]> frameByte = new List<byte[]>();
if (!subSocket.TryReceiveMultipartBytes(ref frameByte)) continue;
//UnityEngine.Debug.Log("线程收到一条");
st_Motions stS = new st_Motions();
string tmp = Encoding.UTF8.GetString(frameByte[0]);
stS.m_iOperaType = BitConverter.ToInt32(frameByte[1], 0);
stS.m_sOperaData = new byte[frameByte[1].Length - 4];
stS.area = tmp;
Array.Copy(frameByte[1], 4, stS.m_sOperaData, 0, frameByte[1].Length - 4);
_reciveMessageInThread(stS);
//}
//catch (Exception e)
//{
// UnityEngine.Debug.LogError(_listenerCancelled+"------------" + e.Message);
//}
}
subSocket.Close();
}
NetMQConfig.Cleanup();
UnityEngine.Debug.LogError("接收线程退出:"+typeName);
}
public void SubTopic(string topic)
{
subSocket.Subscribe(topic);
}
public void UnSubtopic(string topic)
{
subSocket.Unsubscribe(topic);
}
public void AddToMono(st_Motions st)
{
_messageReciveStmotion.Add(st);
}
/// <summary>
/// 处理一条byte[]消息
/// </summary>
public void UpdateByte()
{
if (_messageReciveStmotion.Count > 0)
{
List<st_Motions> tmps = _messageReciveStmotion.GetRange(0, _messageReciveStmotion.Count);
tmps.ForEach(data =>
{
if (data.m_sOperaData != null)
{
_reciveMessageInMono(data);
UnityEngine.Debug.Log("处理:" + data.m_iOperaType + "st_motion" + "------" + data.m_sOperaData.Length);
}
else
{
UnityEngine.Debug.LogError(data.m_iOperaType + "st_motion结构错误");
}
});
_messageReciveStmotion.RemoveRange(0, tmps.Count);
}
}
}

View File

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

View File

@ -0,0 +1,107 @@
using NetMQ;
using NetMQ.Sockets;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
/// <summary>
/// 发布模块
/// </summary>
public class NetMqPublisher
{
private string serverPubIP;
private Thread _listenerWorker;
public bool _listenerCancelled;
/// <summary>
/// 自定义名称
/// </summary>
public string typeName;
public delegate void MessageDelegateByte(st_Motions st);
private readonly MessageDelegateByte _messageDelegateByte;
/// <summary>
/// 发送队列
/// </summary>
private readonly ConcurrentQueue<st_Motions> _messageQueueData = new ConcurrentQueue<st_Motions>();
public NetMqPublisher(string pubIP)
{
serverPubIP = pubIP;
StartListen();
}
/// <summary>
/// 开始监听
/// </summary>
public void StartListen()
{
_listenerCancelled = false;
_listenerWorker = new Thread(ByteListenerWork);
_listenerWorker.IsBackground = true;
_listenerWorker.Start();
}
/// <summary>
/// 停止监听
/// </summary>
public void StopListen()
{
_listenerCancelled = true;
//_listenerWorker.Join();
}
/// <summary>
/// 发送线程
/// </summary>
private void ByteListenerWork()
{
AsyncIO.ForceDotNet.Force();
using (var publishSocket = new PublisherSocket())
{
publishSocket.Options.ReceiveHighWatermark = 1000;
publishSocket.Connect(serverPubIP);
UnityEngine.Debug.Log("客户端开启成功:"+ serverPubIP);
while (!_listenerCancelled)
{
if (!_messageQueueData.IsEmpty)
{
if (_messageQueueData.TryDequeue(out st_Motions sendData))
{
if(_listenerCancelled)
{
UnityEngine.Debug.LogError("_listenerCancelled="+true);
}
byte[] tmpbytes = new byte[4 + sendData.m_sOperaData.Length];
Array.Copy(BitConverter.GetBytes(sendData.m_iOperaType), 0, tmpbytes, 0, 4);
Array.Copy(sendData.m_sOperaData, 0, tmpbytes, 4, sendData.m_sOperaData.Length);
if (!_listenerCancelled && !publishSocket.SendMoreFrame(sendData.area).TrySendFrame(tmpbytes)) continue;
UnityEngine.Debug.Log("发送一个消息:" + sendData.area + "," + sendData.m_iOperaType);
}
}
}
publishSocket.Close();
}
NetMQConfig.Cleanup();
UnityEngine.Debug.LogError("发送线程退出:"+typeName);
}
public void AddMessageToSendQue(string area, int type, byte[] data)
{
st_Motions sendData = new st_Motions { area = area, m_iOperaType = type, m_sOperaData = data };
_messageQueueData.Enqueue(sendData);
}
public void AddMessageToSendQue(st_Motions st)
{
if (!string.IsNullOrEmpty(st.area))
{
_messageQueueData.Enqueue(st);
}
else
{
UnityEngine.Debug.LogError("area空:type=" + st.m_iOperaType);
}
}
}

View File

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

View File

@ -187,8 +187,3 @@ public class AuthReq
public string userCode;
public string userName;
}
public class DisplayOnly : PropertyAttribute
{
}