client 追加本地连接管理

This commit is contained in:
sin365 2024-01-22 11:56:02 +08:00
parent f0212fdebf
commit e7ad09e7eb
8 changed files with 237 additions and 127 deletions

View File

@ -0,0 +1,31 @@
using NoSugarNet.ClientCore.Manager;
using NoSugarNet.ClientCore.Network;
using ServerCore.Manager;
namespace NoSugarNet.ClientCore
{
public class AppNoSugarNet
{
public static string TokenStr;
public static long RID = -1;
public static string IP;
public static int Port;
public static LogManager log;
public static NetworkHelper networkHelper;
public static AppLogin login;
public static AppChat chat;
public static AppLocalClient local;
public static UserDataManager user;
public static void Init(string IP, int port)
{
log = new LogManager();
networkHelper = new NetworkHelper();
login = new AppLogin();
chat = new AppChat();
local = new AppLocalClient();
user = new UserDataManager();
networkHelper.Init(IP, port);
}
}
}

View File

@ -1,21 +1,19 @@
using AxibugProtobuf;
using NoSugarNet.ClientCore.Network;
using Google.Protobuf;
using System.Net.Sockets;
using NoSugarNet.ClientCore.Common;
using HaoYueNet.ServerNetwork;
using NoSugarNet.ClientCore;
using static System.Runtime.InteropServices.JavaScript.JSType;
using NoSugarNet.ClientCore.Manager;
using NoSugarNet.ClientCore.Common;
using NoSugarNet.ClientCore.Network;
using System.Net;
namespace ServerCore.Manager
{
public class AppLocalClient
{
Dictionary<byte, Protobuf_Cfgs_Single> mDictTunnelID2Cfg = new Dictionary<byte, Protobuf_Cfgs_Single>();
Dictionary<byte, LocalListener> mDictTunnelID2Listeners = new Dictionary<byte, LocalListener>();
CompressAdapter mCompressAdapter;
public LocalMsgQueuePool _localMsgPool = new LocalMsgQueuePool(1000);
public AppLocalClient()
{
@ -55,7 +53,6 @@ namespace ServerCore.Manager
mDictTunnelID2Listeners[_listener.mTunnelID] = _listener;
}
}
/// <summary>
/// 删除监听
/// </summary>
@ -67,11 +64,10 @@ namespace ServerCore.Manager
{
if (mDictTunnelID2Listeners.ContainsKey(_listener.mTunnelID))
{
mDictTunnelID2Listeners[_listener.mTunnelID] = _listener;
mDictTunnelID2Listeners.Remove(_listener.mTunnelID);
}
}
}
bool GetLocalListener(byte tunnelId,out LocalListener _listener)
{
_listener = null;
@ -81,12 +77,26 @@ namespace ServerCore.Manager
_listener = mDictTunnelID2Listeners[tunnelId];
return true;
}
public void StopAll()
{
lock (mDictTunnelID2Listeners)
{
byte[] keys = mDictTunnelID2Listeners.Keys.ToArray();
for (int i = 0; i < keys.Length; i++)
{
LocalListener _listener = mDictTunnelID2Listeners[keys[i]];
_listener.StopAll();
_listener.Stop();
RemoveLocalListener(_listener);
}
}
}
#endregion
#region
public void Recive_CmdCfgs(byte[] reqData)
{
App.log.Debug("Recive_CmdCfgs");
AppNoSugarNet.log.Debug("Recive_CmdCfgs");
Protobuf_Cfgs msg = ProtoBufHelper.DeSerizlize<Protobuf_Cfgs>(reqData);
for (int i = 0;msg.Cfgs.Count > 0;i++)
@ -96,22 +106,21 @@ namespace ServerCore.Manager
}
InitListenerMode();
}
public void Recive_TunnelS2CConnect(byte[] reqData)
{
App.log.Debug("Recive_TunnelS2CConnect");
AppNoSugarNet.log.Debug("Recive_TunnelS2CConnect");
Protobuf_S2C_Connect msg = ProtoBufHelper.DeSerizlize<Protobuf_S2C_Connect>(reqData);
OnServerLocalConnect((byte)msg.TunnelID,(byte)msg.Idx);
}
public void Recive_TunnelS2CDisconnect(byte[] reqData)
{
App.log.Debug("Recive_TunnelS2CDisconnect");
AppNoSugarNet.log.Debug("Recive_TunnelS2CDisconnect");
Protobuf_S2C_Disconnect msg = ProtoBufHelper.DeSerizlize<Protobuf_S2C_Disconnect>(reqData);
OnServerLocalDisconnect((byte)msg.TunnelID,(byte)msg.Idx);
}
public void Recive_TunnelS2CData(byte[] reqData)
{
App.log.Debug("Recive_TunnelS2CData");
AppNoSugarNet.log.Debug("Recive_TunnelS2CData");
Protobuf_S2C_DATA msg = ProtoBufHelper.DeSerizlize<Protobuf_S2C_DATA>(reqData);
OnServerLocalDataCallBack((byte)msg.TunnelID,(byte)msg.Idx, msg.HunterNetCoreData.ToArray());
}
@ -135,9 +144,8 @@ namespace ServerCore.Manager
});
//告知给服务端,来自客户端本地的连接建立
App.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SConnect, respData);
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SConnect, respData);
}
/// <summary>
/// 当客户端本地端口连接断开
/// </summary>
@ -155,9 +163,8 @@ namespace ServerCore.Manager
Idx= _Idx,
});
//告知给服务端,来自客户端本地的连接断开
App.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SDisconnect, respData);
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SDisconnect, respData);
}
/// <summary>
/// 当服务端本地端口连接
/// </summary>
@ -166,9 +173,17 @@ namespace ServerCore.Manager
{
if (!GetLocalListener(tunnelId, out LocalListener _listener))
return;
//TODO 维护本地状态
//维护状态
_listener.SetRemoteConnectd(Idx, true);
if (_listener.GetDictMsgQueue(Idx, out List<IdxWithMsg> msglist))
{
for(int i = 0; i < msglist.Count; i++)
{
//投递给服务端,来自客户端本地的连接数据
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SData, msglist[i].data);
}
}
}
/// <summary>
/// 当服务端本地端口连接断开
/// </summary>
@ -178,9 +193,10 @@ namespace ServerCore.Manager
{
if (!GetLocalListener(tunnelId, out LocalListener _listener))
return;
_listener.SetRemoteConnectd(Idx,false);
_listener.CloseConnectByIdx(Idx);
}
#endregion
#region
@ -194,12 +210,10 @@ namespace ServerCore.Manager
{
if (!GetLocalListener(tunnelId, out LocalListener _listener))
return;
//解压
data = mCompressAdapter.Decompress(data);
_listener.SendSocketByIdx(Idx,data);
}
/// <summary>
/// 来自客户端本地连接投递的Tunnel数据
/// </summary>
@ -217,8 +231,18 @@ namespace ServerCore.Manager
HunterNetCoreData = ByteString.CopyFrom(data)
});
if (!GetLocalListener(tunnelId, out LocalListener _listener))
return;
//远程未连接,添加到缓存
if (!_listener.CheckRemoteConnect(Idx))
{
_listener.EnqueueIdxWithMsg(Idx, respData);
return;
}
//投递给服务端,来自客户端本地的连接数据
App.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SData, respData);
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SData, respData);
}
#endregion
}

View File

@ -17,7 +17,7 @@ namespace NoSugarNet.ClientCore.Manager
LoginType = 0,
Account = Account,
};
App.networkHelper.SendToServer((int)CommandID.CmdLogin, ProtoBufHelper.Serizlize(msg));
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdLogin, ProtoBufHelper.Serizlize(msg));
}
public void RecvLoginMsg(byte[] reqData)
@ -25,12 +25,12 @@ namespace NoSugarNet.ClientCore.Manager
Protobuf_Login_RESP msg = ProtoBufHelper.DeSerizlize<Protobuf_Login_RESP>(reqData);
if (msg.Status == LoginResultStatus.Ok)
{
App.log.Debug("登录成功");
App.user.InitMainUserData(App.user.userdata.Account);
AppNoSugarNet.log.Debug("登录成功");
AppNoSugarNet.user.InitMainUserData(AppNoSugarNet.user.userdata.Account);
}
else
{
App.log.Debug("登录失败");
AppNoSugarNet.log.Debug("登录失败");
}
}

View File

@ -1,74 +0,0 @@
//using HaoYueNet.ClientNetwork.OtherMode;
//namespace NoSugarNet.ClientCore
//{
// /// <summary>
// /// 继承网络库,以支持网络功能
// /// </summary>
// public class LocalClient : NetworkHelperCore_ListenerMode
// {
// public byte mTunnelID;
// public LocalClient(byte TunnelID)
// {
// mTunnelID = TunnelID;
// //指定接收服务器数据事件
// OnReceiveData += GetDataCallBack;
// //断开连接
// OnClose += OnConnectClose;
// OnConnected += NetworkConnected;
// //网络库调试信息输出事件,用于打印网络内容
// OnLogOut += NetworkDeBugLog;
// }
// public void NetworkConnected(bool IsConnect)
// {
// NetworkDeBugLog($"LocalListener_Connected:{IsConnect}");
// if (IsConnect)
// {
// App.local.OnClientLocalConnect(mTunnelID,this);
// }
// else
// {
// //连接失败
// NetworkDeBugLog("连接失败!");
// }
// }
// public void NetworkDeBugLog(string str)
// {
// //用于Unity内的输出
// //Debug.Log("NetCoreDebug >> "+str);
// Console.WriteLine("LocalListener_Debug >> " + str);
// }
// /// <summary>
// /// 接受包回调
// /// </summary>
// /// <param name="CMDID">协议ID</param>
// /// <param name="ERRCODE">错误编号</param>
// /// <param name="data">业务数据</param>
// public void GetDataCallBack(byte[] data)
// {
// NetworkDeBugLog("收到消息 数据长度=>" + data.Length);
// try
// {
// //抛出网络数据
// App.local.OnClientTunnelDataCallBack(mTunnelID, data);
// }
// catch (Exception ex)
// {
// NetworkDeBugLog("逻辑处理错误:" + ex.ToString());
// }
// }
// /// <summary>
// /// 关闭连接
// /// </summary>
// public void OnConnectClose()
// {
// NetworkDeBugLog("LocalListener_OnConnectClose");
// App.local.OnClientLocalDisconnect(mTunnelID,this);
// }
// }
//}

View File

@ -26,9 +26,9 @@ namespace NoSugarNet.ClientCore
if (num > 0)
{
int Idx = AddDictSocket(token.Socket);
if (GetSocketByIdx(Idx, out Socket _socket))
if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInf))
{
App.local.OnClientLocalConnect(mTunnelID, (byte)Idx);
AppNoSugarNet.local.OnClientLocalConnect(mTunnelID, (byte)Idx);
}
}
}
@ -40,9 +40,9 @@ namespace NoSugarNet.ClientCore
/// <param name="data"></param>
public void SendSocketByIdx(int Idx, byte[] data)
{
if (GetSocketByIdx(Idx, out Socket _socket))
if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
{
SendToSocket(_socket, data);
SendToSocket(_localClientInfo._socket, data);
}
//TODO连接前缓存数据
}
@ -60,14 +60,14 @@ namespace NoSugarNet.ClientCore
public void DataCallBack(Socket sk, byte[] data)
{
App.log.Debug("收到消息 数据长度=>" + data.Length);
AppNoSugarNet.log.Debug("收到消息 数据长度=>" + data.Length);
if (!GetSocketIdxBySocket(sk, out int Idx))
return;
try
{
//抛出网络数据
App.local.OnClientTunnelDataCallBack(mTunnelID, (byte)Idx, data);
AppNoSugarNet.local.OnClientTunnelDataCallBack(mTunnelID, (byte)Idx, data);
}
catch (Exception ex)
{
@ -77,9 +77,9 @@ namespace NoSugarNet.ClientCore
public void CloseConnectByIdx(byte Idx)
{
if (GetSocketByIdx(Idx, out Socket _socket))
if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInf))
{
_socket.Shutdown(SocketShutdown.Both);
_localClientInf._socket.Shutdown(SocketShutdown.Both);
}
}
@ -94,20 +94,28 @@ namespace NoSugarNet.ClientCore
if (!GetSocketIdxBySocket(token.Socket, out int Idx))
return;
App.local.OnClientLocalConnect(mTunnelID, (byte)Idx);
AppNoSugarNet.local.OnClientLocalDisconnect(mTunnelID, (byte)Idx);
RemoveDictSocket(token.Socket);
}
public void OnShowNetLog(string msg)
{
App.log.Debug(msg);
AppNoSugarNet.log.Debug(msg);
}
#region
Dictionary<nint, int> DictSocketHandle2Idx = new Dictionary<nint, int>();
Dictionary<int, Socket> DictIdx2Socket = new Dictionary<int, Socket>();
Dictionary<int, LocalClientInfo> DictIdx2LocalClientInfo = new Dictionary<int, LocalClientInfo>();
int mSeedIdx = 0;
List<int> FreeIdxs = new List<int>();
public class LocalClientInfo
{
public Socket _socket;
public bool bRemoteConnect;
public bool bLocalConnect => _socket.Connected;
public Queue<IdxWithMsg> msgQueue = new Queue<IdxWithMsg>();
}
int GetNextIdx()
{
if (FreeIdxs.Count > 0)
@ -132,7 +140,7 @@ namespace NoSugarNet.ClientCore
{
int Idx = GetNextIdx();
DictSocketHandle2Idx[socket.Handle] = Idx;
DictIdx2Socket[Idx] = socket;
DictIdx2LocalClientInfo[Idx] = new LocalClientInfo() { _socket = socket,bRemoteConnect = false};
return Idx;
}
}
@ -147,21 +155,21 @@ namespace NoSugarNet.ClientCore
return;
int Idx = DictSocketHandle2Idx[socket.Handle];
FreeIdxs.Add(Idx);
if (DictIdx2Socket.ContainsKey(Idx))
DictIdx2Socket.Remove(Idx);
if (DictIdx2LocalClientInfo.ContainsKey(Idx))
DictIdx2LocalClientInfo.Remove(Idx);
DictSocketHandle2Idx.Remove(socket.Handle);
}
}
public bool GetSocketByIdx(int Idx, out Socket _socket)
bool GetSocketByIdx(int Idx, out LocalClientInfo _localClientInfo)
{
if (!DictIdx2Socket.ContainsKey(Idx))
if (!DictIdx2LocalClientInfo.ContainsKey(Idx))
{
_socket = null;
_localClientInfo = null;
return false;
}
_socket = DictIdx2Socket[Idx];
_localClientInfo = DictIdx2LocalClientInfo[Idx];
return true;
}
@ -182,6 +190,72 @@ namespace NoSugarNet.ClientCore
Idx = DictSocketHandle2Idx[_socket.Handle];
return true;
}
public bool CheckRemoteConnect(int Idx)
{
if (!GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
return false;
return _localClientInfo.bRemoteConnect;
}
public void SetRemoteConnectd(int Idx,bool bConnected)
{
if (!GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
return;
if (bConnected)
AppNoSugarNet.log.Debug("远端本地连接已连接");
else
AppNoSugarNet.log.Debug("远端本地连接已断开连接");
_localClientInfo.bRemoteConnect = bConnected;
}
public void StopAll()
{
lock (DictIdx2LocalClientInfo)
{
int[] Idxs = DictIdx2LocalClientInfo.Keys.ToArray();
for (int i = 0; i < Idxs.Length; i++)
{
CloseConnectByIdx((byte)Idxs[i]);
}
DictIdx2LocalClientInfo.Clear();
}
}
#endregion
#region
public void EnqueueIdxWithMsg(byte Idx, byte[] data)
{
if (!GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
return;
IdxWithMsg Msg = AppNoSugarNet.local._localMsgPool.Dequeue();
Msg.Idx = Idx;
Msg.data = data;
_localClientInfo.msgQueue.Enqueue(Msg);
}
public bool GetDictMsgQueue(byte Idx,out List<IdxWithMsg> MsgList)
{
if (!GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo) || _localClientInfo.msgQueue.Count < 1)
{
MsgList = null;
return false;
}
MsgList = new List<IdxWithMsg>();
lock (_localClientInfo.msgQueue)
{
while (_localClientInfo.msgQueue.Count > 0)
{
IdxWithMsg msg = _localClientInfo.msgQueue.Dequeue();
MsgList.Add(msg);
AppNoSugarNet.local._localMsgPool.Enqueue(msg);
}
return true;
}
}
#endregion
}
}

View File

@ -0,0 +1,53 @@
namespace HaoYueNet.ServerNetwork
{
public class IdxWithMsg
{
public byte Idx;
public byte[] data;
}
public class LocalMsgQueuePool
{
Queue<IdxWithMsg> msg_pool;
public LocalMsgQueuePool(int capacity)
{
msg_pool = new Queue<IdxWithMsg>(capacity);
}
/// <summary>
/// 向 Queue 的末尾添加一个对象。
/// </summary>
/// <param name="item"></param>
public void Enqueue(IdxWithMsg item)
{
lock (msg_pool)
{
item.Idx = 0;
item.data = null;
msg_pool.Enqueue(item);
}
}
//移除并返回在 Queue 的开头的对象。
public IdxWithMsg Dequeue()
{
lock (msg_pool)
{
if(msg_pool.Count > 0)
return msg_pool.Dequeue();
return new IdxWithMsg();
}
}
public int Count
{
get { return msg_pool.Count; }
}
public void Clear()
{
msg_pool.Clear();
}
}
}

View File

@ -18,7 +18,7 @@ namespace NoSugarNet.ClientCore.Manager
public UserDataManager()
{
//注册重连成功事件,以便后续自动登录
App.networkHelper.OnReConnected += OnReConnected;
AppNoSugarNet.networkHelper.OnReConnected += OnReConnected;
}
public MainUserDataBase userdata { get;private set; } = new MainUserDataBase();
public bool IsLoggedIn => userdata.IsLoggedIn;
@ -49,7 +49,7 @@ namespace NoSugarNet.ClientCore.Manager
//如果之前已登录,则重新登录
if (userdata.IsLoggedIn)
{
App.login.Login(userdata.Account);
AppNoSugarNet.login.Login(userdata.Account);
}
}
}

View File

@ -44,7 +44,7 @@ namespace NoSugarNet.ClientCore.Network
NetworkDeBugLog($"NetworkConnected:{IsConnect}");
if (IsConnect)
{
AppNoSugarNet.login.Login(Guid.NewGuid().ToString());
}
else
{
@ -81,7 +81,6 @@ namespace NoSugarNet.ClientCore.Network
{
NetworkDeBugLog("逻辑处理错误:" + ex.ToString());
}
}
/// <summary>
@ -91,6 +90,9 @@ namespace NoSugarNet.ClientCore.Network
{
NetworkDeBugLog("OnConnectClose");
//停止所有
AppNoSugarNet.local.StopAll();
//自动重连开关
if (bAutoReConnect)
ReConnect();
@ -112,13 +114,13 @@ namespace NoSugarNet.ClientCore.Network
{
//等待时间
Thread.Sleep(ReConnectTryTime);
App.log.Debug($"尝试自动重连{LastConnectIP}:{LastConnectPort}……");
AppNoSugarNet.log.Debug($"尝试自动重连{LastConnectIP}:{LastConnectPort}……");
//第一步
if (Init(LastConnectIP, LastConnectPort))
{
App.log.Debug($"自动重连成功!");
AppNoSugarNet.log.Debug($"自动重连成功!");
bflagDone = true;
App.log.Debug($"触发重连后的自动逻辑!");
AppNoSugarNet.log.Debug($"触发重连后的自动逻辑!");
OnReConnected?.Invoke();
}
} while (!bflagDone);