提交 6c066f6c 编写于 作者: K kongran

网络底层首次提交

上级 e92b5c4d
Library
Temp
Assembly-CSharp-Editor.csproj
Assembly-CSharp.csproj
.idea
obj
fileFormatVersion: 2
guid: e757f305a2ad6e142bc575cd815529ed
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using UnityEngine; using UnityEngine;
using UnityEngine.UI; using UnityEngine.UI;
using Object = UnityEngine.Object; using Object = UnityEngine.Object;
namespace ZFramework.Core namespace ZFramework.Core
{ {
public class AssetReference : MonoBehaviour public class AssetReference : MonoBehaviour
{ {
private readonly Dictionary<string, AssetData> _refAssets = new Dictionary<string, AssetData>(); private readonly Dictionary<string, AssetData> _refAssets = new Dictionary<string, AssetData>();
protected struct UserData protected struct UserData
{ {
public UnityEngine.Object Owner; public UnityEngine.Object Owner;
public System.Type AssetType; public System.Type AssetType;
public string AssetPath; public string AssetPath;
public int Index; public int Index;
public string SubAssetName; public string SubAssetName;
public bool IsAsync; public bool IsAsync;
} }
public void Load<T>(UnityEngine.Object owner, string path, int index, bool bAsync) where T : UnityEngine.Object public void Load<T>(UnityEngine.Object owner, string path, int index, bool bAsync) where T : UnityEngine.Object
{ {
UserData userData = new UserData() {Owner = owner,AssetPath = path, Index = index,IsAsync = bAsync,AssetType = typeof(T),SubAssetName = null}; UserData userData = new UserData() {Owner = owner,AssetPath = path, Index = index,IsAsync = bAsync,AssetType = typeof(T),SubAssetName = null};
Load(userData); Load(userData);
} }
private void Load(UserData userData) private void Load(UserData userData)
{ {
int splitIndex = userData.AssetPath.LastIndexOf('#'); //对于图集这类的资源,获取图集内的某张图片,其路径为 图集路径#图片名 如 atlas#sprite1.png; int splitIndex = userData.AssetPath.LastIndexOf('#'); //对于图集这类的资源,获取图集内的某张图片,其路径为 图集路径#图片名 如 atlas#sprite1.png;
string resPath; string resPath;
bool bWithSubAssets; bool bWithSubAssets;
if (splitIndex > 0) if (splitIndex > 0)
{ {
resPath = userData.AssetPath.Substring(0, splitIndex); resPath = userData.AssetPath.Substring(0, splitIndex);
userData.SubAssetName = userData.AssetPath.Substring(splitIndex + 1); userData.SubAssetName = userData.AssetPath.Substring(splitIndex + 1);
bWithSubAssets = true; bWithSubAssets = true;
} }
else else
{ {
resPath = userData.AssetPath; resPath = userData.AssetPath;
bWithSubAssets = false; bWithSubAssets = false;
} }
if (userData.IsAsync) if (userData.IsAsync)
{ {
} }
else else
{ {
onAssetLoadComplete(userData, AssetManager.Instance.LoadAsset(resPath, bWithSubAssets)); onAssetLoadComplete(userData, AssetManager.Instance.LoadAsset(resPath, bWithSubAssets));
} }
} }
void onAssetLoadComplete(UserData userData, AssetData assetData) void onAssetLoadComplete(UserData userData, AssetData assetData)
{ {
if (assetData == null) if (assetData == null)
return; return;
UnityEngine.Object newObject = string.IsNullOrEmpty(userData.SubAssetName) UnityEngine.Object newObject = string.IsNullOrEmpty(userData.SubAssetName)
? assetData.AssetObject ? assetData.AssetObject
: assetData[userData.SubAssetName]; : assetData[userData.SubAssetName];
if (newObject != null) if (newObject != null)
{ {
UpdateReference(userData,assetData); //更新引用计数 UpdateReference(userData,assetData); //更新引用计数
SetAssetObject(userData, newObject); SetAssetObject(userData, newObject);
} }
else else
{ {
assetData.DecRef(); assetData.DecRef();
Debug.LogError($"Can not load {assetData.Path}"); Debug.LogError($"Can not load {assetData.Path}");
} }
} }
//此类可以扩展,这里只写了sprite,还可以有material等资源 //此类可以扩展,这里只写了sprite,还可以有material等资源
protected virtual void SetAssetObject(UserData userData, Object newObject) protected virtual void SetAssetObject(UserData userData, Object newObject)
{ {
if (userData.Owner == null) return; if (userData.Owner == null) return;
if (userData.AssetType == typeof(Sprite)) if (userData.AssetType == typeof(Sprite))
{ {
switch (userData.Owner) switch (userData.Owner)
{ {
case Image image: case Image image:
image.sprite = newObject as Sprite; image.sprite = newObject as Sprite;
break; break;
case SpriteRenderer spriteRenderer: case SpriteRenderer spriteRenderer:
spriteRenderer.sprite = newObject as Sprite; spriteRenderer.sprite = newObject as Sprite;
break; break;
case Button owner: case Button owner:
{ {
Button button = owner; Button button = owner;
SpriteState spriteState = button.spriteState; SpriteState spriteState = button.spriteState;
switch (userData.Index) switch (userData.Index)
{ {
case 0: case 0:
spriteState.highlightedSprite = newObject as Sprite; spriteState.highlightedSprite = newObject as Sprite;
break; break;
case 1: case 1:
spriteState.pressedSprite = newObject as Sprite; spriteState.pressedSprite = newObject as Sprite;
break; break;
#if UNITY_2019_4_OR_NEWER #if UNITY_2019_4_OR_NEWER
case 2: case 2:
spriteState.selectedSprite = newObject as Sprite; spriteState.selectedSprite = newObject as Sprite;
break; break;
#endif #endif
case 3: case 3:
spriteState.disabledSprite = newObject as Sprite; spriteState.disabledSprite = newObject as Sprite;
break; break;
} }
button.spriteState = spriteState; button.spriteState = spriteState;
break; break;
} }
} }
} }
} }
private void UpdateReference(UserData userData , AssetData assetData) private void UpdateReference(UserData userData , AssetData assetData)
{ {
string key = $"{userData.Owner.GetHashCode()}_{userData.AssetType}_{userData.Index}"; string key = $"{userData.Owner.GetHashCode()}_{userData.AssetType}_{userData.Index}";
assetData?.AddRef(); assetData?.AddRef();
if (_refAssets.TryGetValue(key,out var oldAssetData)) if (_refAssets.TryGetValue(key,out var oldAssetData))
{ {
oldAssetData?.DecRef(); oldAssetData?.DecRef();
if(assetData!= null) if(assetData!= null)
{ {
_refAssets[key] = assetData; _refAssets[key] = assetData;
} }
} }
else else
{ {
if(assetData!= null) if(assetData!= null)
{ {
_refAssets.Add(key,assetData); _refAssets.Add(key,assetData);
} }
} }
} }
public void OnDestroy() public void OnDestroy()
{ {
foreach (var _ in _refAssets.Where(_=>_.Value != null)) foreach (var _ in _refAssets.Where(_=>_.Value != null))
{ {
_.Value.DecRef(); _.Value.DecRef();
} }
_refAssets.Clear(); _refAssets.Clear();
} }
} }
} }
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using UnityEngine; using UnityEngine;
using UnityEngine.UI; using UnityEngine.UI;
namespace ZFramework.Core namespace ZFramework.Core
{ {
public static class ComponentExtension public static class ComponentExtension
{ {
static void LoadAsset<T>(Component component, string path, int index,bool bAsync) where T : UnityEngine.Object static void LoadAsset<T>(Component component, string path, int index,bool bAsync) where T : UnityEngine.Object
{ {
AssetReference assetReference = component.GetComponent<AssetReference>(); AssetReference assetReference = component.GetComponent<AssetReference>();
if (assetReference == null) if (assetReference == null)
{ {
assetReference = component.gameObject.AddComponent<AssetReference>(); assetReference = component.gameObject.AddComponent<AssetReference>();
} }
} }
public static void SetSprite(Image image,string path,bool bAsync = false) public static void SetSprite(Image image,string path,bool bAsync = false)
{ {
LoadAsset<Sprite>(image, path, 0, bAsync); LoadAsset<Sprite>(image, path, 0, bAsync);
} }
} }
} }
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using UnityEngine; using UnityEngine;
namespace ZFramework.Core namespace ZFramework.Core
{ {
public class GlobalObjectManager public class GlobalObjectManager
{ {
private static Dictionary<string, GameObject> _gameObjectsDic; private static Dictionary<string, GameObject> _gameObjectsDic;
private static List<IGlobalObject> _objectList; private static List<IGlobalObject> _objectList;
public static void Retain(GameObject go) public static void Retain(GameObject go)
{ {
if (_gameObjectsDic == null) if (_gameObjectsDic == null)
{ {
_gameObjectsDic = new Dictionary<string, GameObject>(); _gameObjectsDic = new Dictionary<string, GameObject>();
} }
if (!_gameObjectsDic.ContainsKey(go.name)) if (!_gameObjectsDic.ContainsKey(go.name))
{ {
_gameObjectsDic.Add(go.name,go); _gameObjectsDic.Add(go.name,go);
if (Application.isPlaying) if (Application.isPlaying)
{ {
UnityEngine.Object.DontDestroyOnLoad(go); UnityEngine.Object.DontDestroyOnLoad(go);
} }
} }
} }
public static void Retain(IGlobalObject go ) public static void Retain(IGlobalObject go )
{ {
if (_objectList == null) if (_objectList == null)
{ {
_objectList = new List<IGlobalObject>(); _objectList = new List<IGlobalObject>();
} }
_objectList.Add(go); _objectList.Add(go);
} }
public static void Release(GameObject go) public static void Release(GameObject go)
{ {
if (_gameObjectsDic!= null && _gameObjectsDic.ContainsKey(go.name)) if (_gameObjectsDic!= null && _gameObjectsDic.ContainsKey(go.name))
{ {
_gameObjectsDic.Remove(go.name); _gameObjectsDic.Remove(go.name);
GameObject.Destroy(go); GameObject.Destroy(go);
} }
} }
public static GameObject GetGameObject(string name) public static GameObject GetGameObject(string name)
{ {
GameObject go = null; GameObject go = null;
if (_gameObjectsDic!= null) if (_gameObjectsDic!= null)
{ {
//return _gameObjectsDic[name]; //return _gameObjectsDic[name];
_gameObjectsDic.TryGetValue(name,out go); _gameObjectsDic.TryGetValue(name,out go);
} }
return go; return go;
} }
} }
} }
namespace ZFramework.Core namespace ZFramework.Core
{ {
public class ResourceManager public class ResourceManager
{ {
} }
} }
\ No newline at end of file
fileFormatVersion: 2 fileFormatVersion: 2
guid: e4d672000c664e40951013068a361b23 guid: e4d672000c664e40951013068a361b23
timeCreated: 1611924612 timeCreated: 1611924612
\ No newline at end of file
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using UnityEngine; using UnityEngine;
namespace ZFramework.Core namespace ZFramework.Core
{ {
public class SingleMonoBehaviorObject<T> : MonoBehaviour where T : SingleMonoBehaviorObject<T> public class SingleMonoBehaviorObject<T> : MonoBehaviour where T : SingleMonoBehaviorObject<T>
{ {
private static T _instance; private static T _instance;
private void Awake() private void Awake()
{ {
if (CheckInstance()) if (CheckInstance())
OnLoad(); OnLoad();
} }
private bool CheckInstance() private bool CheckInstance()
{ {
if (this == Instance) if (this == Instance)
{ {
return true; return true;
} }
Destroy(gameObject); Destroy(gameObject);
return false; return false;
} }
protected virtual void OnLoad() protected virtual void OnLoad()
{ {
} }
protected virtual void OnDestroy() protected virtual void OnDestroy()
{ {
if (_instance == this) if (_instance == this)
{ {
_instance = null; _instance = null;
} }
} }
/// <summary> /// <summary>
/// 判断对象是否有效 /// 判断对象是否有效
/// </summary> /// </summary>
public static bool IsValid public static bool IsValid
{ {
get get
{ {
return _instance != null; return _instance != null;
} }
} }
public static T Active() public static T Active()
{ {
return Instance; return Instance;
} }
/// <summary> /// <summary>
/// 实例化 /// 实例化
/// </summary> /// </summary>
public static T Instance public static T Instance
{ {
get get
{ {
if (_instance == null) if (_instance == null)
{ {
System.Type type = typeof(T); System.Type type = typeof(T);
string name = type.Name; string name = type.Name;
GameObject go = GlobalObjectManager.GetGameObject(name); GameObject go = GlobalObjectManager.GetGameObject(name);
if (go == null) if (go == null)
{ {
go = GameObject.Find($"/{name}"); go = GameObject.Find($"/{name}");
if (go == null) if (go == null)
{ {
go = new GameObject(name); go = new GameObject(name);
go.transform.position = Vector3.one; go.transform.position = Vector3.one;
} }
GlobalObjectManager.Retain(go); GlobalObjectManager.Retain(go);
} }
if (go!= null) if (go!= null)
{ {
_instance = go.GetComponent<T>(); _instance = go.GetComponent<T>();
if (_instance == null) if (_instance == null)
{ {
_instance = go.AddComponent<T>(); _instance = go.AddComponent<T>();
} }
} }
if (_instance == null) if (_instance == null)
{ {
Debug.LogError($"Can't create SingletonBehaviour<{typeof(T)}>"); Debug.LogError($"Can't create SingletonBehaviour<{typeof(T)}>");
} }
} }
return _instance; return _instance;
} }
} }
} }
} }
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using UnityEngine; using UnityEngine;
using ZFramework.Core; using ZFramework.Core;
namespace ZFramework.Core namespace ZFramework.Core
{ {
public interface IGlobalObject public interface IGlobalObject
{ {
void Active(); void Active();
void Release(); void Release();
} }
public abstract class SingleObject <T> : IGlobalObject where T : SingleObject<T>,new() public abstract class SingleObject <T> : IGlobalObject where T : SingleObject<T>,new()
{ {
protected static T _instance; protected static T _instance;
public static T Instance public static T Instance
{ {
get get
{ {
if (_instance == null) if (_instance == null)
{ {
_instance = new T(); _instance = new T();
_instance.Init(); _instance.Init();
GlobalObjectManager.Retain(_instance); GlobalObjectManager.Retain(_instance);
} }
return _instance; return _instance;
} }
} }
public static bool IsValid public static bool IsValid
{ {
get get
{ {
return _instance != null; return _instance != null;
} }
} }
protected virtual void Init() protected virtual void Init()
{ {
} }
public virtual void Active() public virtual void Active()
{ {
} }
public virtual void Release() public virtual void Release()
{ {
} }
} }
} }
using UnityEngine; using UnityEngine;
namespace ZFramework.Core namespace ZFramework.Core
{ {
public class ULogger : SingleObject<ULogger> public class ULogger : SingleObject<ULogger>
{ {
//日志级别 //日志级别
public enum LogLevel public enum LogLevel
{ {
INFO, INFO,
ASSERT, ASSERT,
WARNING, WARNING,
ERROR ERROR
} }
//日志输出媒介 //日志输出媒介
public enum OutputType public enum OutputType
{ {
NONE = 0, NONE = 0,
EDITOR = 0x1, EDITOR = 0x1,
GUI = 0x2, GUI = 0x2,
FILE = 0x3 FILE = 0x3
} }
private LogLevel _logLevel = LogLevel.INFO; private LogLevel _logLevel = LogLevel.INFO;
private OutputType _outputType = OutputType.EDITOR; private OutputType _outputType = OutputType.EDITOR;
private System.IO.StreamWriter _logWriter; private System.IO.StreamWriter _logWriter;
protected override void Init() protected override void Init()
{ {
// default // default
_outputType = OutputType.EDITOR; _outputType = OutputType.EDITOR;
} }
/// <summary> /// <summary>
/// 设置输出媒介 /// 设置输出媒介
/// </summary> /// </summary>
public static void SetOutputType(OutputType type) public static void SetOutputType(OutputType type)
{ {
#if UNITY_2019_4_OR_NEWER #if UNITY_2019_4_OR_NEWER
Instance.ChangeOutputChannel(type); Instance.ChangeOutputChannel(type);
#else #else
if ((type & OutputType.GUI) != 0) if ((type & OutputType.GUI) != 0)
Instance.ChangeOutputChannel(type & ~OutputType.GUI | OutputType.FILE); Instance.ChangeOutputChannel(type & ~OutputType.GUI | OutputType.FILE);
#endif #endif
} }
public void ChangeOutputChannel(OutputType type) public void ChangeOutputChannel(OutputType type)
{ {
if (type != _outputType) if (type != _outputType)
{ {
Dispose(); Dispose();
_outputType = type; _outputType = type;
} }
} }
private void Dispose() private void Dispose()
{ {
if (_logWriter != null) if (_logWriter != null)
{ {
_logWriter.Close(); _logWriter.Close();
_logWriter = null; _logWriter = null;
} }
} }
/// <summary> /// <summary>
/// 设置日志等级 /// 设置日志等级
/// </summary> /// </summary>
public static void SetLogLevel(LogLevel level) public static void SetLogLevel(LogLevel level)
{ {
Instance._logLevel = level; Instance._logLevel = level;
} }
/// <summary> /// <summary>
/// 普通日志输出 /// 普通日志输出
/// </summary> /// </summary>
/// <param name="logStr"></param> /// <param name="logStr"></param>
public void Log(string logStr) public static void Log(string logStr)
{ {
} }
/// <summary> /// <summary>
/// 断言 /// 断言
/// </summary> /// </summary>
/// <param name="condition"></param> /// <param name="condition"></param>
/// <param name="logStr"></param> /// <param name="logStr"></param>
public void LogAssert(bool condition, string logStr) public static void LogAssert(bool condition, string logStr)
{ {
if (!condition) if (!condition)
{ {
} }
} }
/// <summary> /// <summary>
/// 警告 /// 警告
/// </summary> /// </summary>
/// <param name="logStr"></param> /// <param name="logStr"></param>
public void LogWarning(string logStr) public static void LogWarning(string logStr)
{ {
} }
/// <summary> /// <summary>
/// 报错 /// 报错
/// </summary> /// </summary>
/// <param name="logStr"></param> /// <param name="logStr"></param>
public void LogError(string logStr) public static void LogError(string logStr)
{ {
} }
private void Log(LogLevel logLevel, string logString) private void Log(LogLevel logLevel, string logString)
{ {
if (logLevel < _logLevel) if (logLevel < _logLevel)
return; return;
switch (_outputType) switch (_outputType)
{ {
case OutputType.NONE: case OutputType.NONE:
return; return;
case OutputType.GUI: case OutputType.GUI:
return; return;
; ;
//todu //todu
case OutputType.FILE: case OutputType.FILE:
WriteLogFile(GetFormatString(logLevel, logString, true)); WriteLogFile(GetFormatString(logLevel, logString, true));
return; return;
case OutputType.EDITOR: case OutputType.EDITOR:
string info = GetFormatString(logLevel, logString, false); string info = GetFormatString(logLevel, logString, false);
switch (logLevel) switch (logLevel)
{ {
case LogLevel.INFO: case LogLevel.INFO:
Debug.Log(info); Debug.Log(info);
break; break;
case LogLevel.ASSERT: case LogLevel.ASSERT:
Debug.LogAssertion(info); Debug.LogAssertion(info);
break; break;
case LogLevel.WARNING: case LogLevel.WARNING:
Debug.LogWarning(info); Debug.LogWarning(info);
break; break;
case LogLevel.ERROR: case LogLevel.ERROR:
Debug.LogError(info); Debug.LogError(info);
break; break;
} }
return; return;
} }
} }
private void WriteLogFile(string logString) private void WriteLogFile(string logString)
{ {
if (_logWriter != null) if (_logWriter != null)
{ {
_logWriter.WriteLine(logString); _logWriter.WriteLine(logString);
_logWriter.Flush(); _logWriter.Flush();
; ;
} }
} }
/// <summary> /// <summary>
/// 对日志进行格式化,主要是颜色的处理 /// 对日志进行格式化,主要是颜色的处理
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
private string GetFormatString(LogLevel logLevel, string logString, bool bColor) private string GetFormatString(LogLevel logLevel, string logString, bool bColor)
{ {
string formatedString = null; string formatedString = null;
switch (logLevel) switch (logLevel)
{ {
case LogLevel.INFO: case LogLevel.INFO:
formatedString = formatedString =
string.Format(bColor ? "[INFO][{0}] - <color=gray>{1}</color>" : "[INFO][{0}] - {1}", string.Format(bColor ? "[INFO][{0}] - <color=gray>{1}</color>" : "[INFO][{0}] - {1}",
System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"), logString); System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"), logString);
break; break;
case LogLevel.ASSERT: case LogLevel.ASSERT:
formatedString = formatedString =
string.Format(bColor ? "[ASSERT][{0}] - <color=green>{1}</color>" : "[ASSERT][{0}] - {1}", string.Format(bColor ? "[ASSERT][{0}] - <color=green>{1}</color>" : "[ASSERT][{0}] - {1}",
System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"), logString); System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"), logString);
break; break;
case LogLevel.WARNING: case LogLevel.WARNING:
formatedString = formatedString =
string.Format(bColor ? "[WARNING][{0}] - <color=yellow>{1}</color>" : "[WARNING][{0}] - {1}", string.Format(bColor ? "[WARNING][{0}] - <color=yellow>{1}</color>" : "[WARNING][{0}] - {1}",
System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"), logString); System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"), logString);
break; break;
case LogLevel.ERROR: case LogLevel.ERROR:
formatedString = formatedString =
string.Format(bColor ? "[ERROR][{0}] - <color=red>{1}</color>" : "[ERROR][{0}] - {1}", string.Format(bColor ? "[ERROR][{0}] - <color=red>{1}</color>" : "[ERROR][{0}] - {1}",
System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"), logString); System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"), logString);
break; break;
} }
return formatedString; return formatedString;
} }
} }
} }
\ No newline at end of file
fileFormatVersion: 2
guid: 994a265236269534c81272244feec749
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
//-----------------------------------------------------------------------
// Copyright (c) Xiaofeng All rights reserved.
// Author: Xiaof_Zheng
// Date: 2022-05-23 11:01:12
//-----------------------------------------------------------------------
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using UnityEngine;
namespace Script.Framework.Net
{
public abstract class Connection : System.IDisposable
{
public string Id { get; set; }
public string BytesPreSending { get; set; }
public bool IsConnected { get; set; } //是否已经连接
public bool IsConnecting { get; set; } //是否正在连接
protected Socket _socket;
protected IPEndPoint _ipEndPoint;
private List<ConnectionEvent> _connectionEvents = new List<ConnectionEvent>();
private object _eventObject = new object();
// 构造函数
public Connection(string address, int port)
{
Id = GetConnectId(address, port);
_ipEndPoint = GetEndPoint(address, port);
}
public static string GetConnectId(string address, int port)
{
return $"{address}:{port}";
}
public static IPEndPoint GetEndPoint(string address, int port)
{
if (string.IsNullOrEmpty(address))
return null;
IPAddress ipAddress;
if (!IPAddress.TryParse(address,out ipAddress))
{
bool bSupportIPv4 = false;
IPAddress[] hostAddresses = Dns.GetHostAddresses(address); // 获取到的可能是ipv4或者ipv6
if (hostAddresses.Length <= 0)
{
Debug.LogError($"DNS look up error : {address}");
return null;
}
for (int i = 0; i < hostAddresses.Length; ++i)
{
if (hostAddresses[i].AddressFamily == AddressFamily.InterNetwork)
{
bSupportIPv4 = true;
ipAddress = hostAddresses[i];
break;
}
}
if (!bSupportIPv4)
ipAddress = hostAddresses[0];
}
return new IPEndPoint(ipAddress, port);
}
public abstract bool Connect();
public virtual void OnError(NetErrorCode errorCode)
{
lock (_eventObject)
{
_connectionEvents.Add(new ConnectionEvent(ConnectionEvent.Type.OnError,(int)errorCode));
}
}
protected virtual void OnDisconnected()
{
lock (_eventObject)
{
_connectionEvents.Add(new ConnectionEvent(ConnectionEvent.Type.OnDisConnected));
}
}
public void Dispose()
{
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 03c79a246dbf96c40b9b2846d4985c29
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
namespace Script.Framework.Net
{
public struct ConnectionEvent
{
public enum Type
{
OnConnected,
OnDisConnected,
OnError
}
public ConnectionEvent(Type type, int param = 0)
{
this.type = type;
this.param = param;
}
public Type type;
public int param;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: fa40a37aa92a69a43b7e002d8f2c77cd
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
//-----------------------------------------------------------------------
// Copyright (c) Xiaofeng. All rights reserved.
// Author: Xiaof_Zheng
// Date: 2022-05-23 13:54:32
//-----------------------------------------------------------------------
namespace Script.Framework.Net
{
public class HttpConnection : Connection
{
public HttpConnection(string address, int port) : base(address, port)
{
}
public override bool Connect()
{
return true;
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: e56ff200229150045abc075400fc79c6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
namespace Script.Framework.Net
{
public enum NetErrorCode
{
IsConnecting = -1000,
ConnectUnstable = -1001,
// SocketError
SocketError = -1,
Success = 0,
OperationAborted = 995,
IOPending = 997,
Interrupted = 10004,
AccessDenied = 10013,
Fault = 10014,
InvalidArgument = 10022,
TooManyOpenSockets = 10024,
WouldBlock = 10035,
InProgress = 10036,
AlreadyInProgress = 10037,
NotSocket = 10038,
DestinationAddressRequired = 10039,
MessageSize = 10040,
ProtocolType = 10041,
ProtocolOption = 10042,
ProtocolNotSupported = 10043,
SocketNotSupported = 10044,
OperationNotSupported = 10045,
ProtocolFamilyNotSupported = 10046,
AddressFamilyNotSupported = 10047,
AddressAlreadyInUse = 10048,
AddressNotAvailable = 10049,
NetworkDown = 10050,
NetworkUnreachable = 10051,
NetworkReset = 10052,
ConnectionAborted = 10053,
ConnectionReset = 10054,
NoBufferSpaceAvailable = 10055,
IsConnected = 10056,
NotConnected = 10057,
Shutdown = 10058,
TimedOut = 10060,
ConnectionRefused = 10061,
HostDown = 10064,
HostUnreachable = 10065,
ProcessLimit = 10067,
SystemNotReady = 10091,
VersionNotSupported = 10092,
NotInitialized = 10093,
Disconnecting = 10101,
TypeNotFound = 10109,
HostNotFound = 11001,
TryAgain = 11002,
NoRecovery = 11003,
NoData = 11004
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: eaef303af641523448fa1d2798103187
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
//-----------------------------------------------------------------------
// Copyright (c) Xiaofeng All rights reserved.
// Author: Xiaof_Zheng
// Date: 2022-05-23 10:48:51
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using ZFramework.Core;
namespace Script.Framework.Net
{
public class NetManager : SingleMonoBehaviorObject<NetManager>
{
private Dictionary<string, Connection> _connections = new Dictionary<string, Connection>();
public HttpConnection GetHttpConnection(string address, int port)
{
//Connection connection;
if (!_connections.TryGetValue(Connection.GetConnectId(address,port),out Connection connection))
{
connection = new HttpConnection(address,port);
_connections.Add(connection.Id,connection);
}
return connection as HttpConnection;
}
public TcpConnection GetTcpConnection(string address, int port)
{
//Connection connection;
if (!_connections.TryGetValue(Connection.GetConnectId(address,port),out Connection connection))
{
connection = new TcpConnection(address,port);
_connections.Add(connection.Id,connection);
}
return connection as TcpConnection;
}
public UdpConnection GetUdpConnection(string address, int port)
{
//Connection connection;
if (!_connections.TryGetValue(Connection.GetConnectId(address,port),out Connection connection))
{
connection = new UdpConnection(address,port);
_connections.Add(connection.Id,connection);
}
return connection as UdpConnection;
}
private void Update()
{
}
public void DestroyConnection(Connection connection)
{
if (_connections.ContainsKey(connection.Id))
{
connection.Dispose();
_connections.Remove(connection.Id);
}
else
{
ULogger.LogError($"Try to destroy a unknown connection : {connection.Id}");
}
}
protected override void OnDestroy()
{
foreach (var connection in _connections)
{
connection.Value.Dispose();
}
base.OnDestroy();
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 7898a293da24fc74c8675e2975cdef68
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
//-----------------------------------------------------------------------
// Copyright (c) Xiaofeng. All rights reserved.
// Author: Xiaof_Zheng
// Date: 2022-05-23 13:55:17
//-----------------------------------------------------------------------
using System.Diagnostics;
using System.Net.Sockets;
using Unity.Collections;
namespace Script.Framework.Net
{
public class TcpConnection : Connection
{
private SocketAsyncEventArgs _connectEventArg;
private SocketAsyncEventArgs _receiverEventArg;
private SocketAsyncEventArgs _sendEventArg;
public TcpConnection(string address, int port) : base(address, port)
{
}
public override bool Connect()
{
return ConnectAsync();
}
public bool ConnectAsync()
{
if (IsConnected || IsConnecting)
{
if (IsConnected)
OnError(NetErrorCode.IsConnected);
else
OnError(NetErrorCode.IsConnecting);
return false;
}
_connectEventArg = new SocketAsyncEventArgs();
_connectEventArg.RemoteEndPoint = _ipEndPoint;
_connectEventArg.Completed += OnAsyncCompleted;
_receiverEventArg = new SocketAsyncEventArgs();
_receiverEventArg.Completed += OnAsyncCompleted;
_sendEventArg = new SocketAsyncEventArgs();
_sendEventArg.Completed += OnAsyncCompleted;
_socket = new Socket(_ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if (_ipEndPoint.AddressFamily == AddressFamily.InterNetworkV6)
_socket.DualMode = true;
IsConnecting = true;
if (!_socket.ConnectAsync(_connectEventArg))
{
ProcessConnect(_connectEventArg);
}
return true;
}
private void OnAsyncCompleted(object sender, SocketAsyncEventArgs socketAsyncEventArgs)
{
switch (socketAsyncEventArgs.LastOperation)
{
case SocketAsyncOperation.Connect:
ProcessConnect(socketAsyncEventArgs);
break;
case SocketAsyncOperation.Receive:
break;
case SocketAsyncOperation.Send:
break;
}
}
private void ProcessConnect(SocketAsyncEventArgs socketAsyncEventArgs)
{
IsConnecting = false;
if (socketAsyncEventArgs.SocketError == SocketError.Success)
{
}
else
{
OnError((NetErrorCode)socketAsyncEventArgs.SocketError);
OnDisconnected();
}
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 87ed8c5e6f6c3e14c841d7ba53068a41
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
//-----------------------------------------------------------------------
// Copyright (c) Xiaofeng All rights reserved.
// Author: Xiaof_Zheng
// Date: 2022-05-23 13:55:50
//-----------------------------------------------------------------------
namespace Script.Framework.Net
{
public class UdpConnection : Connection
{
public UdpConnection(string address, int port) : base(address, port)
{
}
public override bool Connect()
{
return true;
}
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 072f78ba508a1ba438df2f8b939b2042
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册