standard2支持

This commit is contained in:
sin365 2024-10-18 16:47:32 +08:00
parent 105986549a
commit a289cb6562
43 changed files with 2349 additions and 1678 deletions

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<_LastSelectedProfileId>F:\Sin365\NoSugarNet\NoSugarNet.Adapter\Properties\PublishProfiles\FolderProfile.pubxml</_LastSelectedProfileId>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,73 @@
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;
namespace NoSugarNet.ClientCli
{
public class ConfigDataModel
{
public string ServerIP { get; set; }
public int ServerPort { get; set; }
public int CompressAdapterType { get; set; }
public List<ConfigDataModel_Single> TunnelList { get; set; }
}
public class ConfigDataModel_Single
{
public string LocalTargetIP { get; set; }
public int LocalTargetPort { get; set; }
public int RemoteLocalPort { get; set; }
}
public static class Config
{
public static ConfigDataModel cfg;
public static bool LoadConfig()
{
try
{
string path = System.Environment.CurrentDirectory + "//config.cfg";
if (!File.Exists(path))
{
ConfigDataModel sampleCfg = new ConfigDataModel
{
ServerIP = "127.0.0.1",
ServerPort = 1000,
TunnelList = new List<ConfigDataModel_Single>()
{
new ConfigDataModel_Single(){ LocalTargetIP = "127.0.0.1",LocalTargetPort=3389,RemoteLocalPort = 20001},
new ConfigDataModel_Single(){ LocalTargetIP = "127.0.0.1",LocalTargetPort=3389,RemoteLocalPort = 20002}
}
};
string jsonString = JsonSerializer.Serialize(sampleCfg, new JsonSerializerOptions()
{
// 整齐打印
WriteIndented = true,
//重新编码,解决中文乱码问题
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)
});
System.IO.File.WriteAllText(path, jsonString, Encoding.UTF8);
Console.WriteLine("未找到配置,已生成模板,请浏览" + path);
return false;
}
StreamReader sr = new StreamReader(path, Encoding.Default);
String jsonstr = sr.ReadToEnd();
cfg = JsonSerializer.Deserialize<ConfigDataModel>(jsonstr);
sr.Close();
if (cfg?.TunnelList.Count > 0)
return true;
else
return false;
}
catch (Exception ex)
{
Console.WriteLine("配置文件异常:" + ex.ToString());
return false;
}
}
}
}

View File

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\NoSugarNet.ClientCore.Standard2\NoSugarNet.ClientCore.Standard2.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,77 @@
using NoSugarNet.ClientCore;
using NoSugarNet.ClientCore.Common;
namespace NoSugarNet.ClientCli.Standard2
{
internal class Program
{
static string Title = "NoSugarNetClient";
static void Main(string[] args)
{
if (!Config.LoadConfig())
{
Console.WriteLine("配置文件错误");
Console.ReadLine();
return;
}
AppNoSugarNet.OnUpdateStatus += OnUpdateStatus;
Dictionary<byte, TunnelClientData> dictTunnel = new Dictionary<byte, TunnelClientData>();
for (int i = 0; i < Config.cfg.TunnelList.Count; i++)
{
ConfigDataModel_Single cfgSingle = Config.cfg.TunnelList[i];
dictTunnel[(byte)i] = new TunnelClientData()
{
TunnelId = (byte)i,
LocalTargetIP = cfgSingle.LocalTargetIP,
LocalTargetPort = (ushort)cfgSingle.LocalTargetPort,
RemoteLocalPort = (ushort)cfgSingle.RemoteLocalPort,
};
}
AppNoSugarNet.Init(dictTunnel, Config.cfg.CompressAdapterType, OnNoSugarNetLog);
AppNoSugarNet.Connect(Config.cfg.ServerIP, Config.cfg.ServerPort);
while (true)
{
string CommandStr = Console.ReadLine();
string Command = "";
Command = ((CommandStr.IndexOf(" ") <= 0) ? CommandStr : CommandStr.Substring(0, CommandStr.IndexOf(" ")));
string[] CmdArr = CommandStr.Split(' ');
switch (Command)
{
case "con":
AppNoSugarNet.Connect(Config.cfg.ServerIP, Config.cfg.ServerPort);
break;
case "tlist":
AppNoSugarNet.forwardlocal.GetClientCount(out int ClientUserCount, out int TunnelCount);
Console.WriteLine($"GetClientCount->{ClientUserCount} TunnelCount->{TunnelCount}");
AppNoSugarNet.forwardlocal.GetClientDebugInfo();
break;
case "stop":
AppNoSugarNet.Close();
break;
default:
break;
}
}
}
static void OnUpdateStatus(NetStatus Forward_NetStatus, NetStatus Reverse_NetStatus)
{
string info = $"Forward: t:{Forward_NetStatus.TunnelCount} r:{ConvertBytesToKilobytes(Forward_NetStatus.srcReciveSecSpeed)}K/s|{ConvertBytesToKilobytes(Forward_NetStatus.tReciveSecSpeed)}K/s s: {ConvertBytesToKilobytes(Forward_NetStatus.srcSendSecSpeed)}K/s|{ConvertBytesToKilobytes(Forward_NetStatus.tSendSecSpeed)}K/s" +
$"| Reverse t:{Reverse_NetStatus.TunnelCount} r:{ConvertBytesToKilobytes(Reverse_NetStatus.srcReciveSecSpeed)}K/s|{ConvertBytesToKilobytes(Reverse_NetStatus.tReciveSecSpeed)}K/s s: {ConvertBytesToKilobytes(Reverse_NetStatus.srcSendSecSpeed)}K/s|{ConvertBytesToKilobytes(Reverse_NetStatus.tSendSecSpeed)}K/s";
Console.Title = Title + info;
Console.WriteLine(info);
}
static string ConvertBytesToKilobytes(long bytes)
{
return Math.Round((double)bytes / 1024, 2).ToString("F2");
}
static void OnNoSugarNetLog(int LogLevel, string msg)
{
Console.WriteLine(msg);
}
}
}

View File

@ -1,9 +1,12 @@
using NoSugarNet.ClientCoreNet.Standard2.Manager;
using NoSugarNet.ClientCoreNet.Standard2.Network;
using NoSugarNet.Adapter.DataHelper;
using NoSugarNet.ClientCore.Common;
using NoSugarNet.ClientCore.Manager;
using NoSugarNet.ClientCore.Network;
using ServerCore.Manager;
using static NoSugarNet.ClientCoreNet.Standard2.Manager.LogManager;
using System.Collections.Generic;
using static NoSugarNet.ClientCore.Manager.LogManager;
namespace NoSugarNet.ClientCoreNet.Standard2
namespace NoSugarNet.ClientCore
{
public class AppNoSugarNet
{
@ -15,28 +18,35 @@ namespace NoSugarNet.ClientCoreNet.Standard2
public static NetworkHelper networkHelper;
public static AppLogin login;
public static AppChat chat;
public static AppLocalClient local;
public static AppForwardLocalClient forwardlocal;
public static AppReverseLocalClient reverselocal;
public static UserDataManager user;
public static System.Timers.Timer _SpeedCheckTimeTimer;//速度检测计时器
public static int TimerInterval = 1000;//计时器间隔
static NetStatus netStatus;
static NetStatus Forward_NetStatus;
static NetStatus Reverse_NetStatus;
#region
public delegate void OnUpdateStatusHandler(NetStatus Status);
public delegate void OnUpdateStatusHandler(NetStatus ForwardStatus, NetStatus ReverseStatus);
public static event OnUpdateStatusHandler OnUpdateStatus;
#endregion
public static void Init(OnLogHandler onLog = null)
public static void Init(Dictionary<byte, TunnelClientData> cfgs, int compressAdapterType = 0,OnLogHandler onLog = null)
{
Config.cfgs = cfgs;
Config.compressAdapterType = (E_CompressAdapter)compressAdapterType;
log = new LogManager();
if(onLog != null)
LogManager.OnLog += onLog;
networkHelper = new NetworkHelper();
login = new AppLogin();
chat = new AppChat();
local = new AppLocalClient();
forwardlocal = new AppForwardLocalClient();
reverselocal = new AppReverseLocalClient(Config.compressAdapterType);
user = new UserDataManager();
netStatus = new NetStatus();
Forward_NetStatus = new NetStatus();
Reverse_NetStatus = new NetStatus();
_SpeedCheckTimeTimer = new System.Timers.Timer();
_SpeedCheckTimeTimer.Interval = TimerInterval;
_SpeedCheckTimeTimer.Elapsed += Checktimer_Elapsed;
@ -53,7 +63,7 @@ namespace NoSugarNet.ClientCoreNet.Standard2
public static void Close()
{
local.StopAll();
forwardlocal.StopAll();
networkHelper.CloseConntect();
AppNoSugarNet.log.Info("停止");
_SpeedCheckTimeTimer.Enabled = false;
@ -61,24 +71,45 @@ namespace NoSugarNet.ClientCoreNet.Standard2
static void Checktimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
local.GetCurrLenght(out long resultReciveAllLenght, out long resultSendAllLenght);
local.GetClientCount(out int ClientUserCount, out int TunnelCount);
NetStatus resutnetStatus = new NetStatus()
{
TunnelCount = TunnelCount,
ClientUserCount = ClientUserCount,
srcSendAllLenght = resultSendAllLenght,
srcReciveAllLenght = resultReciveAllLenght,
srcReciveSecSpeed = (resultReciveAllLenght - netStatus.srcReciveAllLenght) / (TimerInterval / 1000),
srcSendSecSpeed = (resultSendAllLenght - netStatus.srcSendAllLenght) / (TimerInterval / 1000),
tSendAllLenght = local.tSendAllLenght,
tReciveAllLenght = local.tReciveAllLenght,
tSendSecSpeed = (local.tSendAllLenght - netStatus.tSendAllLenght) / (TimerInterval / 1000),
tReciveSecSpeed = (local.tReciveAllLenght - netStatus.tReciveAllLenght) / (TimerInterval / 1000),
};
netStatus = resutnetStatus;
OnUpdateStatus?.Invoke(resutnetStatus);
forwardlocal.GetCurrLenght(out long resultReciveAllLenght, out long resultSendAllLenght);
forwardlocal.GetClientCount(out int ClientUserCount, out int TunnelCount);
NetStatus resutnetStatus = new NetStatus()
{
TunnelCount = TunnelCount,
ClientUserCount = ClientUserCount,
srcSendAllLenght = resultSendAllLenght,
srcReciveAllLenght = resultReciveAllLenght,
srcReciveSecSpeed = (resultReciveAllLenght - Forward_NetStatus.srcReciveAllLenght) / (TimerInterval / 1000),
srcSendSecSpeed = (resultSendAllLenght - Forward_NetStatus.srcSendAllLenght) / (TimerInterval / 1000),
tSendAllLenght = forwardlocal.tSendAllLenght,
tReciveAllLenght = forwardlocal.tReciveAllLenght,
tSendSecSpeed = (forwardlocal.tSendAllLenght - Forward_NetStatus.tSendAllLenght) / (TimerInterval / 1000),
tReciveSecSpeed = (forwardlocal.tReciveAllLenght - Forward_NetStatus.tReciveAllLenght) / (TimerInterval / 1000),
};
Forward_NetStatus = resutnetStatus;
}
{
reverselocal.GetCurrLenght(out long resultReciveAllLenght, out long resultSendAllLenght);
reverselocal.GetClientCount(out int ClientUserCount, out int TunnelCount);
NetStatus resutnetStatus = new NetStatus()
{
TunnelCount = TunnelCount,
ClientUserCount = ClientUserCount,
srcSendAllLenght = resultSendAllLenght,
srcReciveAllLenght = resultReciveAllLenght,
srcReciveSecSpeed = (resultReciveAllLenght - Reverse_NetStatus.srcReciveAllLenght) / (TimerInterval / 1000),
srcSendSecSpeed = (resultSendAllLenght - Reverse_NetStatus.srcSendAllLenght) / (TimerInterval / 1000),
tSendAllLenght = reverselocal.tSendAllLenght,
tReciveAllLenght = reverselocal.tReciveAllLenght,
tSendSecSpeed = (reverselocal.tSendAllLenght - Reverse_NetStatus.tSendAllLenght) / (TimerInterval / 1000),
tReciveSecSpeed = (reverselocal.tReciveAllLenght - Reverse_NetStatus.tReciveAllLenght) / (TimerInterval / 1000),
};
Reverse_NetStatus = resutnetStatus;
}
OnUpdateStatus?.Invoke(Forward_NetStatus , Reverse_NetStatus);
}
}
}

View File

@ -0,0 +1,18 @@
using NoSugarNet.Adapter.DataHelper;
using System.Collections.Generic;
namespace NoSugarNet.ClientCore.Common
{
public struct TunnelClientData
{
public byte TunnelId;
public string LocalTargetIP;
public ushort LocalTargetPort;
public ushort RemoteLocalPort;
}
public static class Config
{
public static Dictionary<byte, TunnelClientData> cfgs = new Dictionary<byte, TunnelClientData>();
public static E_CompressAdapter compressAdapterType;
}
}

View File

@ -1,6 +1,6 @@
using System;
namespace NoSugarNet.ClientCoreNet.Standard2.Common
namespace NoSugarNet.ClientCore.Common
{
public static class Helper
{

View File

@ -1,7 +1,7 @@
using Google.Protobuf;
using System;
namespace NoSugarNet.ClientCoreNet.Standard2.Common
namespace NoSugarNet.ClientCore.Common
{
public static class ProtoBufHelper
{

View File

@ -1,4 +1,4 @@
namespace NoSugarNet.ClientCoreNet.Standard2.Event
namespace NoSugarNet.ClientCore.Event
{
public enum EEvent
{

View File

@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
namespace NoSugarNet.ClientCoreNet.Standard2.Event
namespace NoSugarNet.ClientCore.Event
{
public class EventData
{

View File

@ -1,9 +1,9 @@
using AxibugProtobuf;
using NoSugarNet.ClientCoreNet.Standard2.Common;
using NoSugarNet.ClientCoreNet.Standard2.Event;
using NoSugarNet.ClientCoreNet.Standard2.Network;
using NoSugarNet.ClientCore.Common;
using NoSugarNet.ClientCore.Event;
using NoSugarNet.ClientCore.Network;
namespace NoSugarNet.ClientCoreNet.Standard2.Manager
namespace NoSugarNet.ClientCore.Manager
{
public class AppChat
{

View File

@ -1,34 +1,32 @@
using AxibugProtobuf;
using Google.Protobuf;
using NoSugarNet.ClientCoreNet.Standard2;
using NoSugarNet.ClientCoreNet.Standard2.Common;
using NoSugarNet.ClientCoreNet.Standard2.Network;
using NoSugarNet.DataHelper;
using NoSugarNet.Adapter;
using NoSugarNet.Adapter.DataHelper;
using NoSugarNet.ClientCore;
using NoSugarNet.ClientCore.Common;
using NoSugarNet.ClientCore.Network;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace ServerCore.Manager
{
public class AppLocalClient
public class AppForwardLocalClient
{
Dictionary<byte, Protobuf_Cfgs_Single> mDictTunnelID2Cfg = new Dictionary<byte, Protobuf_Cfgs_Single>();
Dictionary<byte, LocalListener> mDictTunnelID2Listeners = new Dictionary<byte, LocalListener>();
CompressAdapter mCompressAdapter;
E_CompressAdapter compressAdapterType;
public LocalMsgQueuePool _localMsgPool = new LocalMsgQueuePool(1000);
Dictionary<byte, ForwardLocalListener> mDictTunnelID2Listeners = new Dictionary<byte, ForwardLocalListener>();
NoSugarNet.Adapter.DataHelper.E_CompressAdapter compressAdapterType;
public long tReciveAllLenght { get; private set; }
public long tSendAllLenght { get; private set; }
public AppLocalClient()
public AppForwardLocalClient()
{
//注册网络消息
NetMsg.Instance.RegNetMsgEvent((int)CommandID.CmdCfgs, Recive_CmdCfgs);
NetMsg.Instance.RegNetMsgEvent((int)CommandID.CmdTunnelS2CConnect, Recive_TunnelS2CConnect);
NetMsg.Instance.RegNetMsgEvent((int)CommandID.CmdTunnelS2CDisconnect, Recive_TunnelS2CDisconnect);
NetMsg.Instance.RegNetMsgEvent((int)CommandID.CmdTunnelS2CData, Recive_TunnelS2CData);
NetMsg.Instance.RegNetMsgEvent((int)CommandID.CmdServerCfgs, Recive_CmdCfgs);
NetMsg.Instance.RegNetMsgEvent((int)CommandID.CmdTunnelS2CForwardConnect, Recive_TunnelS2CConnect);
NetMsg.Instance.RegNetMsgEvent((int)CommandID.CmdTunnelS2CForwardDisconnect, Recive_TunnelS2CDisconnect);
NetMsg.Instance.RegNetMsgEvent((int)CommandID.CmdTunnelS2CForwardData, Recive_TunnelS2CData);
}
public void GetCurrLenght(out long resultReciveAllLenght, out long resultSendAllLenght)
@ -51,20 +49,40 @@ namespace ServerCore.Manager
ClientUserCount = mDictTunnelID2Listeners.Count;
}
public void GetClientDebugInfo()
{
AppNoSugarNet.log.Debug($"------------ mDictTunnelID2Listeners {mDictTunnelID2Listeners.Count} ------------");
lock (mDictTunnelID2Listeners)
{
foreach (var item in mDictTunnelID2Listeners)
{
var cinfo = item.Value.GetDictIdx2LocalClientInfo();
AppNoSugarNet.log.Debug($"----- TunnelID {item.Key} ObjcurrSeed->{item.Value.currSeed} ClientList->{item.Value.ClientList.Count} Idx2LocalClient->{cinfo.Count} -----");
foreach (var c in cinfo)
{
AppNoSugarNet.log.Debug($"----- Idx {c.Key} bRemoteConnect->{c.Value.bRemoteConnect} msgQueue.Count->{c.Value.msgQueue.Count} -----");
}
}
}
}
/// <summary>
/// 初始化连接,先获取到配置
/// </summary>
void InitListenerMode()
{
AppNoSugarNet.log.Info("初始化压缩适配器" + compressAdapterType);
//初始化压缩适配器,代表压缩类型
mCompressAdapter = new CompressAdapter(compressAdapterType);
////初始化压缩适配器,代表压缩类型
//mCompressAdapter = new NoSugarNet.Adapter.DataHelper.CompressAdapter(compressAdapterType);
foreach (var cfg in mDictTunnelID2Cfg)
{
LocalListener listener = new LocalListener(256, 1024, cfg.Key);
ForwardLocalListener listener = new ForwardLocalListener(256, 1024, cfg.Key,AppNoSugarNet.user.userdata.UID);
AppNoSugarNet.log.Info($"开始监听配置 Tunnel:{cfg.Key},Port:{cfg.Value.Port}");
listener.Init();
listener.Start(new IPEndPoint(IPAddress.Any.Address, (int)cfg.Value.Port));
listener.BandEvent(AppNoSugarNet.log.Log, OnClientLocalConnect, OnClientLocalDisconnect, OnClientTunnelDataCallBack);
listener.StartListener((uint)cfg.Value.Port);
//listener.Init();
//listener.Start(new IPEndPoint(IPAddress.Any.Address, (int)cfg.Value.Port));
//listener.Init((int)cfg.Value.Port);
AddLocalListener(listener);
}
@ -77,7 +95,7 @@ namespace ServerCore.Manager
/// </summary>
/// <param name="tunnelId"></param>
/// <param name="serverClient"></param>
void AddLocalListener(LocalListener _listener)
void AddLocalListener(ForwardLocalListener _listener)
{
lock (mDictTunnelID2Listeners)
{
@ -89,7 +107,7 @@ namespace ServerCore.Manager
/// </summary>
/// <param name="tunnelId"></param>
/// <param name="serverClient"></param>
void RemoveLocalListener(LocalListener _listener)
void RemoveLocalListener(ForwardLocalListener _listener)
{
lock (mDictTunnelID2Listeners)
{
@ -99,7 +117,7 @@ namespace ServerCore.Manager
}
}
}
bool GetLocalListener(byte tunnelId,out LocalListener _listener)
bool GetLocalListener(byte tunnelId,out ForwardLocalListener _listener)
{
_listener = null;
if (!mDictTunnelID2Listeners.ContainsKey(tunnelId))
@ -115,11 +133,13 @@ namespace ServerCore.Manager
byte[] keys = mDictTunnelID2Listeners.Keys.ToArray();
for (int i = 0; i < keys.Length; i++)
{
LocalListener _listener = mDictTunnelID2Listeners[keys[i]];
_listener.StopAll();
ForwardLocalListener _listener = mDictTunnelID2Listeners[keys[i]];
_listener.StopAllLocalClient();
_listener.StopWithClear();
//_listener.Stop();
RemoveLocalListener(_listener);
}
mDictTunnelID2Listeners.Clear();
}
}
#endregion
@ -127,7 +147,7 @@ namespace ServerCore.Manager
#region
public void Recive_CmdCfgs(byte[] reqData)
{
AppNoSugarNet.log.Debug("Recive_CmdCfgs");
AppNoSugarNet.log.Debug("Forward->Recive_CmdCfgs");
Protobuf_Cfgs msg = ProtoBufHelper.DeSerizlize<Protobuf_Cfgs>(reqData);
for (int i = 0;i < msg.Cfgs.Count;i++)
@ -135,29 +155,28 @@ namespace ServerCore.Manager
Protobuf_Cfgs_Single cfg = msg.Cfgs[i];
mDictTunnelID2Cfg[(byte)cfg.TunnelID] = cfg;
}
compressAdapterType = (E_CompressAdapter)msg.CompressAdapterType;
compressAdapterType = (NoSugarNet.Adapter.DataHelper.E_CompressAdapter)msg.CompressAdapterType;
InitListenerMode();
}
public void Recive_TunnelS2CConnect(byte[] reqData)
{
AppNoSugarNet.log.Debug("Recive_TunnelS2CConnect");
Protobuf_S2C_Connect msg = ProtoBufHelper.DeSerizlize<Protobuf_S2C_Connect>(reqData);
AppNoSugarNet.log.Debug("Forward->Recive_TunnelS2CConnect");
Protobuf_Tunnel_Connect msg = ProtoBufHelper.DeSerizlize<Protobuf_Tunnel_Connect>(reqData);
if(msg.Connected == 1)
OnServerLocalConnect((byte)msg.TunnelID,(byte)msg.Idx);
OnRemoteLocalConnect((byte)msg.TunnelID,(byte)msg.Idx);
else
OnServerLocalDisconnect((byte)msg.TunnelID, (byte)msg.Idx);
OnRemoteLocalDisconnect((byte)msg.TunnelID, (byte)msg.Idx);
}
public void Recive_TunnelS2CDisconnect(byte[] reqData)
{
AppNoSugarNet.log.Debug("Recive_TunnelS2CDisconnect");
Protobuf_S2C_Disconnect msg = ProtoBufHelper.DeSerizlize<Protobuf_S2C_Disconnect>(reqData);
OnServerLocalDisconnect((byte)msg.TunnelID,(byte)msg.Idx);
AppNoSugarNet.log.Debug("Forward->Recive_TunnelS2CDisconnect");
Protobuf_Tunnel_Disconnect msg = ProtoBufHelper.DeSerizlize<Protobuf_Tunnel_Disconnect>(reqData);
OnRemoteLocalDisconnect((byte)msg.TunnelID,(byte)msg.Idx);
}
public void Recive_TunnelS2CData(byte[] reqData)
{
//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());
Protobuf_Tunnel_DATA msg = ProtoBufHelper.DeSerizlize<Protobuf_Tunnel_DATA>(reqData);
OnRemoteLocalDataCallBack((byte)msg.TunnelID,(byte)msg.Idx, msg.HunterNetCoreData.ToArray());
}
#endregion
@ -167,51 +186,51 @@ namespace ServerCore.Manager
/// </summary>
/// <param name="uid"></param>
/// <param name="tunnelId"></param>
public void OnClientLocalConnect(byte tunnelId,byte _Idx)
public void OnClientLocalConnect(long UID, byte tunnelId,byte _Idx)
{
AppNoSugarNet.log.Debug($"OnClientLocalConnect {tunnelId},{_Idx}");
AppNoSugarNet.log.Debug($"Forward->OnClientLocalConnect {tunnelId},{_Idx}");
if (!mDictTunnelID2Cfg.ContainsKey(tunnelId))
return;
byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_C2S_Connect()
byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_Tunnel_Connect()
{
TunnelID = tunnelId,
Idx = _Idx,
});
//告知给服务端,来自客户端本地的连接建立
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SConnect, respData);
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SForwardConnect, respData);
}
/// <summary>
/// 当客户端本地端口连接断开
/// </summary>
/// <param name="uid"></param>
/// <param name="tunnelId"></param>
public void OnClientLocalDisconnect(byte tunnelId, byte _Idx)
public void OnClientLocalDisconnect(long UID, byte tunnelId, byte _Idx)
{
AppNoSugarNet.log.Debug($"OnClientLocalDisconnect {tunnelId},{_Idx}");
AppNoSugarNet.log.Debug($"Forward->OnClientLocalDisconnect {tunnelId},{_Idx}");
//隧道ID定位投递服务端本地连接
if (!mDictTunnelID2Cfg.ContainsKey(tunnelId))
return;
byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_C2S_Disconnect()
byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_Tunnel_Disconnect()
{
TunnelID = tunnelId,
Idx= _Idx,
});
//告知给服务端,来自客户端本地的连接断开
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SDisconnect, respData);
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SForwardDisconnect, respData);
}
/// <summary>
/// 当服务端本地端口连接
/// </summary>
/// <param name="tunnelId"></param>
public void OnServerLocalConnect(byte tunnelId,byte Idx)
public void OnRemoteLocalConnect(byte tunnelId,byte Idx)
{
AppNoSugarNet.log.Debug($"OnServerLocalConnect {tunnelId},{Idx}");
if (!GetLocalListener(tunnelId, out LocalListener _listener))
AppNoSugarNet.log.Debug($"Forward->OnRemoteLocalConnect {tunnelId},{Idx}");
if (!GetLocalListener(tunnelId, out ForwardLocalListener _listener))
return;
//维护状态
_listener.SetRemoteConnectd(Idx, true);
@ -221,9 +240,9 @@ namespace ServerCore.Manager
{
IdxWithMsg msg = msglist[i];
//投递给服务端,来自客户端本地的连接数据
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SData, msg.data);
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SForwardData, msg.data);
//发送后回收
AppNoSugarNet.local._localMsgPool.Enqueue(msg);
MsgQueuePool._MsgPool.Enqueue(msg);
}
}
}
@ -232,10 +251,10 @@ namespace ServerCore.Manager
/// </summary>
/// <param name="uid"></param>
/// <param name="tunnelId"></param>
public void OnServerLocalDisconnect(byte tunnelId, byte Idx)
public void OnRemoteLocalDisconnect(byte tunnelId, byte Idx)
{
AppNoSugarNet.log.Debug($"OnServerLocalDisconnect {tunnelId},{Idx}");
if (!GetLocalListener(tunnelId, out LocalListener _listener))
AppNoSugarNet.log.Debug($"Forward->OnRemoteLocalDisconnect {tunnelId},{Idx}");
if (!GetLocalListener(tunnelId, out ForwardLocalListener _listener))
return;
_listener.SetRemoteConnectd(Idx,false);
_listener.CloseConnectByIdx(Idx);
@ -249,15 +268,15 @@ namespace ServerCore.Manager
/// <param name="uid"></param>
/// <param name="tunnelId"></param>
/// <param name="data"></param>
public void OnServerLocalDataCallBack(byte tunnelId,byte Idx, byte[] data)
public void OnRemoteLocalDataCallBack(byte tunnelId,byte Idx, byte[] data)
{
//AppNoSugarNet.log.Info($"OnServerLocalDataCallBack {tunnelId},{Idx},Data长度{data.Length}");
if (!GetLocalListener(tunnelId, out LocalListener _listener))
//AppNoSugarNet.log.Info($"OnRemoteLocalDataCallBack {tunnelId},{Idx},Data长度{data.Length}");
if (!GetLocalListener(tunnelId, out ForwardLocalListener _listener))
return;
//记录压缩前数据长度
tReciveAllLenght += data.Length;
//解压
data = mCompressAdapter.Decompress(data);
data = CompressAdapterSelector.Adapter(compressAdapterType).Decompress(data);
_listener.SendSocketByIdx(Idx,data);
}
/// <summary>
@ -266,16 +285,16 @@ namespace ServerCore.Manager
/// <param name="uid"></param>
/// <param name="tunnelId"></param>
/// <param name="data"></param>
public void OnClientTunnelDataCallBack(byte tunnelId,byte Idx, byte[] data)
public void OnClientTunnelDataCallBack(long UID, byte tunnelId,byte Idx, byte[] data)
{
//AppNoSugarNet.log.Info($"OnClientTunnelDataCallBack {tunnelId},{Idx}");
//AppNoSugarNet.log.Info($"OnClientTunnelDataCallBack {tunnelId},{Idx} data.Length->{data.Length}");
int SlienLenght = 1000;
//判断数据量大时分包
if (data.Length > SlienLenght)
{
byte[] tempSpan = data;
byte[] tempSpanSlien = null;
Span<byte> tempSpan = data;
Span<byte> tempSpanSlien = null;
int PageCount = (int)(data.Length / SlienLenght);
if (data.Length % SlienLenght > 0)
{
@ -284,21 +303,13 @@ namespace ServerCore.Manager
for (int i = 0; i < PageCount; i++)
{
tempSpanSlien = new byte[SlienLenght];
int StartIdx = i * SlienLenght;
if (i != PageCount - 1)//不是最后一个包
Array.Copy(tempSpan, StartIdx, tempSpanSlien, 0, SlienLenght);
else//最后一个
Array.Copy(tempSpan, StartIdx, tempSpanSlien, 0, tempSpanSlien.Length - StartIdx);
SendDataToRemote(tunnelId, Idx, tempSpanSlien);
/*if (i != PageCount - 1)//不是最后一个包
tempSpanSlien = tempSpan.Slice(StartIdx, SlienLenght);
else//最后一个
tempSpanSlien = tempSpan.Slice(StartIdx);
SendDataToRemote(tunnelId, Idx, tempSpanSlien.ToArray());*/
SendDataToRemote(tunnelId, Idx, tempSpanSlien.ToArray());
}
return;
}
@ -308,18 +319,18 @@ namespace ServerCore.Manager
void SendDataToRemote(byte tunnelId, byte Idx, byte[] data)
{
//压缩
data = mCompressAdapter.Compress(data);
data = CompressAdapterSelector.Adapter(compressAdapterType).Compress(data);
//记录压缩后数据长度
tSendAllLenght += data.Length;
byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_C2S_DATA()
byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_Tunnel_DATA()
{
TunnelID = tunnelId,
Idx = Idx,
HunterNetCoreData = ByteString.CopyFrom(data)
});
if (!GetLocalListener(tunnelId, out LocalListener _listener))
if (!GetLocalListener(tunnelId, out ForwardLocalListener _listener))
return;
//远程未连接,添加到缓存
@ -329,7 +340,7 @@ namespace ServerCore.Manager
return;
}
//投递给服务端,来自客户端本地的连接数据
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SData, respData);
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SForwardData, respData);
}
#endregion

View File

@ -1,21 +1,29 @@
using AxibugProtobuf;
using NoSugarNet.ClientCoreNet.Standard2.Common;
using NoSugarNet.ClientCoreNet.Standard2.Network;
using NoSugarNet.ClientCore.Common;
using NoSugarNet.ClientCore.Network;
using System;
namespace NoSugarNet.ClientCoreNet.Standard2.Manager
namespace NoSugarNet.ClientCore.Manager
{
public class AppLogin
{
static string LastLoginGuid = "";
public AppLogin()
{
NetMsg.Instance.RegNetMsgEvent((int)CommandID.CmdLogin, RecvLoginMsg);
}
public void Login(string Account)
public void Login()
{
AppNoSugarNet.log.Debug("-->Login");
if(string.IsNullOrEmpty(LastLoginGuid))
LastLoginGuid = Guid.NewGuid().ToString();
AppNoSugarNet.user.userdata.Account = LastLoginGuid;
Protobuf_Login msg = new Protobuf_Login()
{
LoginType = 0,
Account = Account,
Account = AppNoSugarNet.user.userdata.Account,
};
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdLogin, ProtoBufHelper.Serizlize(msg));
}
@ -26,13 +34,13 @@ namespace NoSugarNet.ClientCoreNet.Standard2.Manager
if (msg.Status == LoginResultStatus.Ok)
{
AppNoSugarNet.log.Info("登录成功");
AppNoSugarNet.user.InitMainUserData(AppNoSugarNet.user.userdata.Account);
AppNoSugarNet.user.InitMainUserData(AppNoSugarNet.user.userdata.Account,msg.UID);
AppNoSugarNet.reverselocal.Send_ClientCfg();
}
else
{
AppNoSugarNet.log.Info("登录失败");
}
}
}
}

View File

@ -0,0 +1,365 @@
using AxibugProtobuf;
using Google.Protobuf;
using NoSugarNet.Adapter;
using NoSugarNet.Adapter.DataHelper;
using NoSugarNet.ClientCore;
using NoSugarNet.ClientCore.Common;
using NoSugarNet.ClientCore.Network;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace ServerCore.Manager
{
public class AppReverseLocalClient
{
Dictionary<long, BackwardLocalClient> mDictCommKey2LocalClients = new Dictionary<long, BackwardLocalClient>();
NoSugarNet.Adapter.DataHelper.CompressAdapter mCompressAdapter;
//public LocalMsgQueuePool _localMsgPool = new LocalMsgQueuePool(1000);
public long tReciveAllLenght { get; private set; }
public long tSendAllLenght { get; private set; }
Protobuf_Cfgs _Send_Protobuf_Cfgs = new Protobuf_Cfgs();
static long GetCommKey(long Uid, int Tunnel, int Idx)
{
return (Uid * 10000000) + (Tunnel * 10000) + Idx;
}
static long GetUidForCommKey(long CommKey)
{
return CommKey / 10000000;
}
public AppReverseLocalClient(NoSugarNet.Adapter.DataHelper.E_CompressAdapter compressAdapterType)
{
AppNoSugarNet.log.Debug("Reverse->初始化压缩适配器" + compressAdapterType);
//初始化压缩适配器暂时使用0代表压缩类型
mCompressAdapter = new CompressAdapter(compressAdapterType);
//注册网络消息
NetMsg.Instance.RegNetMsgEvent((int)CommandID.CmdTunnelS2CReverseConnect, Recive_TunnelS2CConnect);
NetMsg.Instance.RegNetMsgEvent((int)CommandID.CmdTunnelS2CReverseDisconnect, Recive_TunnelS2CDisconnect);
NetMsg.Instance.RegNetMsgEvent((int)CommandID.CmdTunnelS2CReverseData, Recive_TunnelS2CData);
}
public void GetCurrLenght(out long resultReciveAllLenght, out long resultSendAllLenght)
{
resultReciveAllLenght = 0;
resultSendAllLenght = 0;
long[] Keys = mDictCommKey2LocalClients.Keys.ToArray();
for (int i = 0; i < Keys.Length; i++)
{
//local和转发 收发相反
resultSendAllLenght += mDictCommKey2LocalClients[Keys[i]].mReciveAllLenght;
resultReciveAllLenght += mDictCommKey2LocalClients[Keys[i]].mSendAllLenght;
}
}
public void Send_ClientCfg()
{
AppNoSugarNet.log.Debug("Reverse->-->Send_ClientCfg");
_Send_Protobuf_Cfgs.CompressAdapterType = (int)Config.compressAdapterType;
_Send_Protobuf_Cfgs.Cfgs.Clear();
foreach (var cfg in Config.cfgs)
{
_Send_Protobuf_Cfgs.Cfgs.Add(new Protobuf_Cfgs_Single() { Port = cfg.Value.RemoteLocalPort, TunnelID = cfg.Value.TunnelId });
}
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdClientCfgs, ProtoBufHelper.Serizlize(_Send_Protobuf_Cfgs));
}
#region
public void Recive_TunnelS2CConnect(byte[] reqData)
{
AppNoSugarNet.log.Debug("Reverse->Recive_TunnelS2CConnect");
Protobuf_Tunnel_Connect msg = ProtoBufHelper.DeSerizlize<Protobuf_Tunnel_Connect>(reqData);
if (msg.Connected == 1)
OnRemoteLocalConnect((byte)msg.TunnelID, (byte)msg.Idx);
else
OnRemoteLocalDisconnect((byte)msg.TunnelID, (byte)msg.Idx);
}
public void Recive_TunnelS2CDisconnect(byte[] reqData)
{
AppNoSugarNet.log.Debug("Reverse->Recive_TunnelS2CDisconnect");
Protobuf_Tunnel_Disconnect msg = ProtoBufHelper.DeSerizlize<Protobuf_Tunnel_Disconnect>(reqData);
OnRemoteLocalDisconnect((byte)msg.TunnelID, (byte)msg.Idx);
}
public void Recive_TunnelS2CData(byte[] reqData)
{
Protobuf_Tunnel_DATA msg = ProtoBufHelper.DeSerizlize<Protobuf_Tunnel_DATA>(reqData);
OnRemoteTunnelDataCallBack(AppNoSugarNet.user.userdata.UID, (byte)msg.TunnelID, (byte)msg.Idx, msg.HunterNetCoreData.ToArray());
}
#endregion
#region
/// <summary>
/// 当服务端本地端口连接
/// </summary>
/// <param name="tunnelId"></param>
public void OnRemoteLocalConnect(byte tunnelId, byte Idx)
{
AppNoSugarNet.log.Debug($"Reverse->OnRemoteLocalConnect{AppNoSugarNet.user.userdata.UID},{tunnelId},{Idx}");
if (!Config.cfgs.ContainsKey(tunnelId))
return;
//开一个线程去建立连接
Thread thread = new Thread(() =>
{
//服务器本地局域网连接指定端口
TunnelClientData tunnelDataCfg = Config.cfgs[tunnelId];
BackwardLocalClient serverLocalClient = new BackwardLocalClient(AppNoSugarNet.user.userdata.UID, tunnelId, (byte)Idx);
serverLocalClient.BandEvent(AppNoSugarNet.log.Log, OnClientLocalConnect, OnClientLocalDisconnect, OnClientLocalDataCallBack);
//连接成功
if (!serverLocalClient.Init(tunnelDataCfg.LocalTargetIP, tunnelDataCfg.LocalTargetPort))
{
//TODO告知客户端连接失败
byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_Tunnel_Connect()
{
TunnelID = tunnelId,
Idx = (uint)Idx,
Connected = 0//失败
});
//发送给客户端,指定服务端本地端口已连接
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SReverseConnect, respData);
}
});
thread.Start();
}
/// <summary>
/// 当服务端本地端口连接断开
/// </summary>
/// <param name="uid"></param>
/// <param name="tunnelId"></param>
public void OnRemoteLocalDisconnect(byte tunnelId, byte Idx)
{
AppNoSugarNet.log.Debug($"Reverse->OnRemoteLocalDisconnect {AppNoSugarNet.user.userdata.UID},{tunnelId},{Idx}");
//隧道ID定位投递服务端本地连接
if (!GetClientLocalClient(AppNoSugarNet.user.userdata.UID, tunnelId, Idx, out BackwardLocalClient LocalClient))
return;
//断开服务端本地客户端连接
CloseClientLocalClient(AppNoSugarNet.user.userdata.UID, tunnelId, Idx);
}
/// <summary>
/// 当服务端本地端口连接
/// </summary>
/// <param name="uid"></param>
/// <param name="tunnelId"></param>
public void OnClientLocalConnect(long uid, byte tunnelId, byte Idx, BackwardLocalClient serverLocalClient)
{
AppNoSugarNet.log.Debug($"Reverse->OnServerLocalConnect {uid},{tunnelId},{Idx}");
//添加到服务端本地连接列表
AddClientLocalClient(uid, tunnelId, Idx, serverLocalClient);
byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_Tunnel_Connect()
{
TunnelID = tunnelId,
Idx = Idx,
Connected = 1
});
//发送给客户端,指定服务端本地端口已连接
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SReverseConnect, respData);
}
/// <summary>
/// 当服务端本地端口连接断开
/// </summary>
/// <param name="uid"></param>
/// <param name="tunnelId"></param>
public void OnClientLocalDisconnect(long uid, byte tunnelId, byte Idx, BackwardLocalClient serverLocalClient)
{
AppNoSugarNet.log.Debug($"Reverse->OnClientLocalDisconnect {uid},{tunnelId},{Idx}");
//移除到服务端本地连接列表
RemoveClientLocalClient(uid, tunnelId, Idx);
byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_Tunnel_Disconnect()
{
TunnelID = tunnelId,
Idx = Idx,
});
//发送给客户端,指定服务端本地端口连接已断开
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SReverseDisconnect, respData);
}
#endregion
#region
/// <summary>
/// 追加连接
/// </summary>
/// <param name="uid"></param>
/// <param name="tunnelId"></param>
/// <param name="serverClient"></param>
void AddClientLocalClient(long uid, byte tunnelId, byte Idx, BackwardLocalClient serverClient)
{
long CommKey = GetCommKey(uid, tunnelId, Idx);
lock (mDictCommKey2LocalClients)
{
mDictCommKey2LocalClients[CommKey] = serverClient;
}
}
/// <summary>
/// 删除连接
/// </summary>
/// <param name="uid"></param>
/// <param name="tunnelId"></param>
void RemoveClientLocalClient(long uid, byte tunnelId, byte Idx)
{
lock (mDictCommKey2LocalClients)
{
long CommKey = GetCommKey(uid, tunnelId, Idx);
if (!mDictCommKey2LocalClients.ContainsKey(CommKey))
return;
mDictCommKey2LocalClients[CommKey].Release();
mDictCommKey2LocalClients.Remove(CommKey);
}
}
bool GetClientLocalClient(long uid, byte tunnelId, byte Idx, out BackwardLocalClient serverLocalClient)
{
serverLocalClient = null;
long CommKey = GetCommKey(uid, tunnelId, Idx);
if (!mDictCommKey2LocalClients.ContainsKey(CommKey))
return false;
serverLocalClient = mDictCommKey2LocalClients[CommKey];
return true;
}
void CloseClientLocalClient(long uid, byte tunnelId, byte Idx)
{
//隧道ID定位投递服务端本地连接
if (!GetClientLocalClient(uid, tunnelId, Idx, out BackwardLocalClient _LocalClient))
return;
_LocalClient.CloseConntect();
RemoveClientLocalClient(uid, tunnelId, Idx);
}
public void GetClientCount(out int ClientUserCount, out int TunnelCount)
{
TunnelCount = mDictCommKey2LocalClients.Count;
long[] CommIDKeys = mDictCommKey2LocalClients.Keys.ToArray();
List<long> TempHadLocalConnetList = new List<long>();
for (int i = 0; i < CommIDKeys.Length; i++)
{
long uid = GetUidForCommKey(CommIDKeys[i]);
if (!TempHadLocalConnetList.Contains(uid))
TempHadLocalConnetList.Add(uid);
}
ClientUserCount = TempHadLocalConnetList.Count;
}
public void StopAll(long Uid)
{
List<long> TempRemoveCommIDList = new List<long>();
lock (mDictCommKey2LocalClients)
{
long[] CommIDKeys = mDictCommKey2LocalClients.Keys.ToArray();
for (int i = 0; i < CommIDKeys.Length; i++)
{
long CommID = CommIDKeys[i];
long tempUid = GetUidForCommKey(CommID);
if (tempUid == Uid)
TempRemoveCommIDList.Add(CommID);
}
}
for (int i = 0; i < TempRemoveCommIDList.Count; i++)
{
long CommID = TempRemoveCommIDList[i];
if (!mDictCommKey2LocalClients.ContainsKey(CommID))
continue;
BackwardLocalClient _serverLoackClient = mDictCommKey2LocalClients[CommID];
_serverLoackClient.CloseConntect();
}
}
#endregion
#region
/// <summary>
/// 来自客户端本地连接投递的Tunnel数据
/// </summary>
/// <param name="uid"></param>
/// <param name="tunnelId"></param>
/// <param name="data"></param>
public void OnRemoteTunnelDataCallBack(long uid, byte tunnelId, byte Idx, byte[] data)
{
//隧道ID定位投递服务端本地连接
if (!GetClientLocalClient(uid, tunnelId, Idx, out BackwardLocalClient serverLocalClient))
return;
//记录数据长度
tReciveAllLenght += data.Length;
//解压
data = mCompressAdapter.Decompress(data);
//记录数据长度
serverLocalClient.mSendAllLenght += data.LongLength;
//发送给对应服务端本地连接数据
serverLocalClient.SendToServer(data);
}
/// <summary>
/// 来自服务端本地连接投递的Tunnel数据
/// </summary>
/// <param name="uid"></param>
/// <param name="tunnelId"></param>
/// <param name="data"></param>
public void OnClientLocalDataCallBack(long uid, byte tunnelId, byte Idx, byte[] data)
{
//AppNoSugarNet.log.Debug($"Reverse->OnClientLocalDataCallBack {uid},{tunnelId},{Idx},data -> {data.Length}");
int SlienLenght = 1000;
//判断数据量大时分包
if (data.Length > SlienLenght)
{
Span<byte> tempSpan = data;
Span<byte> tempSpanSlien = null;
int PageCount = (int)(data.Length / SlienLenght);
if (data.Length % SlienLenght > 0)
{
PageCount++;
}
for (int i = 0; i < PageCount; i++)
{
int StartIdx = i * SlienLenght;
if (i != PageCount - 1)//不是最后一个包
tempSpanSlien = tempSpan.Slice(StartIdx, SlienLenght);
else//最后一个
tempSpanSlien = tempSpan.Slice(StartIdx);
SendDataToRemote(uid, tunnelId, Idx, tempSpanSlien.ToArray());
}
return;
}
SendDataToRemote(uid, tunnelId, Idx, data);
}
void SendDataToRemote(long uid, byte tunnelId, byte Idx, byte[] data)
{
//压缩
data = mCompressAdapter.Compress(data);
//记录压缩后数据长度
tSendAllLenght += data.Length;
byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_Tunnel_DATA()
{
TunnelID = tunnelId,
Idx = Idx,
HunterNetCoreData = ByteString.CopyFrom(data)
});
//发送给客户端指定客户端本地隧道ID
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SReverseData, respData);
}
#endregion
}
}

View File

@ -1,264 +1,295 @@
using HaoYueNet.ServerNetwork.Standard2;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
//using HaoYueNet.ServerNetwork;
//using System.Net.Sockets;
namespace NoSugarNet.ClientCoreNet.Standard2
{
public class LocalListener : TcpSaeaServer_SourceMode
{
public byte mTunnelID;
public long mReciveAllLenght;
public long mSendAllLenght;
public LocalListener(int numConnections, int receiveBufferSize, byte TunnelID)
: base(numConnections, receiveBufferSize)
{
OnClientNumberChange += ClientNumberChange;
OnReceive += ReceiveData;
OnDisconnected += OnDisconnect;
OnNetLog += OnShowNetLog;
//namespace NoSugarNet.ClientCore
//{
// public class LocalListener : TcpSaeaServer_SourceMode
// {
// public byte mTunnelID;
// public long mReciveAllLenght;
// public long mSendAllLenght;
// public long currSeed;
// static long Seed;
mTunnelID = TunnelID;
}
// public LocalListener(int numConnections, int receiveBufferSize, byte TunnelID)
// : base(numConnections, receiveBufferSize)
// {
// OnClientNumberChange += ClientNumberChange;
// OnReceive += ReceiveData;
// OnDisconnected += OnDisconnect;
// OnNetLog += OnShowNetLog;
private void ClientNumberChange(int num, AsyncUserToken token)
{
AppNoSugarNet.log.Info("Client数发生变化");
//增加连接数
if (num > 0)
{
int Idx = AddDictSocket(token.Socket);
if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInf))
{
AppNoSugarNet.local.OnClientLocalConnect(mTunnelID, (byte)Idx);
}
}
}
// mTunnelID = TunnelID;
/// <summary>
/// 通过下标发送
/// </summary>
/// <param name="Idx"></param>
/// <param name="data"></param>
public void SendSocketByIdx(int Idx, byte[] data)
{
if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
{
mSendAllLenght += data.Length;
SendToSocket(_localClientInfo._socket, data);
}
//TODO连接前缓存数据
}
// currSeed = Seed++;
// }
/// <summary>
/// 接受包回调
/// </summary>
/// <param name="CMDID">协议ID</param>
/// <param name="ERRCODE">错误编号</param>
/// <param name="data">业务数据</param>
private void ReceiveData(AsyncUserToken token, byte[] data)
{
DataCallBack(token.Socket, data);
}
// private void ClientNumberChange(int num, AsyncUserToken token)
// {
// AppNoSugarNet.log.Info("Client数发生变化");
// //增加连接数stsc
// if (num > 0)
// {
// int Idx = AddDictSocket(token.Socket);
// if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInf))
// {
// AppNoSugarNet.local.OnClientLocalConnect(mTunnelID, (byte)Idx);
// }
// }
// }
public void DataCallBack(Socket sk, byte[] data)
{
//AppNoSugarNet.log.Info("收到消息 数据长度=>" + data.Length);
//记录接受长度
mReciveAllLenght += data.Length;
if (!GetSocketIdxBySocket(sk, out int Idx))
return;
try
{
//抛出网络数据
AppNoSugarNet.local.OnClientTunnelDataCallBack(mTunnelID, (byte)Idx, data);
}
catch (Exception ex)
{
AppNoSugarNet.log.Info("逻辑处理错误:" + ex.ToString());
}
}
// /// <summary>
// /// 通过下标发送
// /// </summary>
// /// <param name="Idx"></param>
// /// <param name="data"></param>
// public void SendSocketByIdx(int Idx, byte[] data)
// {
// if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
// {
// mSendAllLenght += data.Length;
// SendToSocket(_localClientInfo._socket, data);
// }
// //TODO连接前缓存数据
// }
public void CloseConnectByIdx(byte Idx)
{
if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInf))
{
_localClientInf._socket.Shutdown(SocketShutdown.Both);
}
}
// /// <summary>
// /// 接受包回调
// /// </summary>
// /// <param name="CMDID">协议ID</param>
// /// <param name="ERRCODE">错误编号</param>
// /// <param name="data">业务数据</param>
// private void ReceiveData(AsyncUserToken token, byte[] data)
// {
// DataCallBack(token.Socket, data);
// }
/// <summary>
/// 断开连接
/// </summary>
/// <param name="sk"></param>
public void OnDisconnect(AsyncUserToken token)
{
AppNoSugarNet.log.Info("断开连接");
// public void DataCallBack(Socket sk, byte[] data)
// {
// //AppNoSugarNet.log.Info("收到消息 数据长度=>" + data.Length);
// //记录接受长度
// mReciveAllLenght += data.Length;
// if (!GetSocketIdxBySocket(sk, out int Idx))
// return;
// try
// {
// //抛出网络数据
// AppNoSugarNet.local.OnClientTunnelDataCallBack(mTunnelID, (byte)Idx, data);
// }
// catch (Exception ex)
// {
// AppNoSugarNet.log.Info("逻辑处理错误:" + ex.ToString());
// }
// }
if (!GetSocketIdxBySocket(token.Socket, out int Idx))
return;
// public void CloseConnectByIdx(byte Idx)
// {
// if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
// {
// //把未发送消息队列回收了
// while (_localClientInfo.msgQueue.Count > 0)
// {
// IdxWithMsg msg = _localClientInfo.msgQueue.Dequeue();
// AppNoSugarNet.local._localMsgPool.Enqueue(msg);
// }
AppNoSugarNet.local.OnClientLocalDisconnect(mTunnelID, (byte)Idx);
RemoveDictSocket(token.Socket);
}
// _localClientInfo._socket.Shutdown(SocketShutdown.Both);
// }
// }
public void OnShowNetLog(string msg)
{
AppNoSugarNet.log.Info(msg);
}
// /// <summary>
// /// 断开连接
// /// </summary>
// /// <param name="sk"></param>
// public void OnDisconnect(AsyncUserToken token)
// {
// AppNoSugarNet.log.Info("断开连接");
#region
Dictionary<IntPtr, int> DictSocketHandle2Idx = new Dictionary<IntPtr, int>();
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>();
}
// if (!GetSocketIdxBySocket(token.Socket, out int Idx))
// return;
int GetNextIdx()
{
if (FreeIdxs.Count > 0)
{
int Idx = FreeIdxs[0];
FreeIdxs.RemoveAt(0);
return Idx;
}
return mSeedIdx++;
}
// AppNoSugarNet.local.OnClientLocalDisconnect(mTunnelID, (byte)Idx);
// RemoveDictSocket(token.Socket);
// }
/// <summary>
/// 追加Socket返回下标
/// </summary>
/// <param name="socket"></param>
/// <returns></returns>
public int AddDictSocket(Socket socket)
{
if (socket == null)
return -1;
lock (DictSocketHandle2Idx)
{
int Idx = GetNextIdx();
DictSocketHandle2Idx[socket.Handle] = Idx;
DictIdx2LocalClientInfo[Idx] = new LocalClientInfo() { _socket = socket,bRemoteConnect = false};
return Idx;
}
}
// public void OnShowNetLog(string msg)
// {
// AppNoSugarNet.log.Info(msg);
// }
public void RemoveDictSocket(Socket socket)
{
if (socket == null)
return;
lock (DictSocketHandle2Idx)
{
if (!DictSocketHandle2Idx.ContainsKey(socket.Handle))
return;
int Idx = DictSocketHandle2Idx[socket.Handle];
FreeIdxs.Add(Idx);
if (DictIdx2LocalClientInfo.ContainsKey(Idx))
DictIdx2LocalClientInfo.Remove(Idx);
DictSocketHandle2Idx.Remove(socket.Handle);
}
}
// #region 一个轻量级无用户连接管理
// Dictionary<IntPtr, int> DictSocketHandle2Idx = new Dictionary<IntPtr, int>();
// 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>();
// }
bool GetSocketByIdx(int Idx, out LocalClientInfo _localClientInfo)
{
if (!DictIdx2LocalClientInfo.ContainsKey(Idx))
{
_localClientInfo = null;
return false;
}
// public Dictionary<int, LocalClientInfo> GetDictIdx2LocalClientInfo()
// {
// return DictIdx2LocalClientInfo;
// }
_localClientInfo = DictIdx2LocalClientInfo[Idx];
return true;
}
// int GetNextIdx()
// {
// if (FreeIdxs.Count > 0)
// {
// int Idx = FreeIdxs[0];
// FreeIdxs.RemoveAt(0);
// return Idx;
// }
// return mSeedIdx++;
// }
public bool GetSocketIdxBySocket(Socket _socket, out int Idx)
{
if (_socket == null)
{
Idx = -1;
return false;
}
// void ResetFree()
// {
// FreeIdxs.Clear();
// mSeedIdx = 0;
// }
if (!DictSocketHandle2Idx.ContainsKey(_socket.Handle))
{
Idx = -1;
return false;
}
// /// <summary>
// /// 追加Socket返回下标
// /// </summary>
// /// <param name="socket"></param>
// /// <returns></returns>
// public int AddDictSocket(Socket socket)
// {
// if (socket == null)
// return -1;
// lock (DictSocketHandle2Idx)
// {
// int Idx = GetNextIdx();
// DictSocketHandle2Idx[socket.Handle] = Idx;
// DictIdx2LocalClientInfo[Idx] = new LocalClientInfo() { _socket = socket,bRemoteConnect = false};
// AppNoSugarNet.log.Debug($"AddDictSocket mTunnelID->{mTunnelID} Idx->{Idx} socket.Handle{socket.Handle}");
// return Idx;
// }
// }
Idx = DictSocketHandle2Idx[_socket.Handle];
return true;
}
// public void RemoveDictSocket(Socket socket)
// {
// if (socket == null)
// return;
// lock (DictSocketHandle2Idx)
// {
// if (!DictSocketHandle2Idx.ContainsKey(socket.Handle))
// return;
// int Idx = DictSocketHandle2Idx[socket.Handle];
// FreeIdxs.Add(Idx);
// if (DictIdx2LocalClientInfo.ContainsKey(Idx))
// DictIdx2LocalClientInfo.Remove(Idx);
// DictSocketHandle2Idx.Remove(socket.Handle);
// AppNoSugarNet.log.Debug($"RemoveDictSocket mTunnelID->{mTunnelID} Idx->{Idx} socket.Handle{socket.Handle}");
// }
// }
public bool CheckRemoteConnect(int Idx)
{
if (!GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
return false;
return _localClientInfo.bRemoteConnect;
}
// bool GetSocketByIdx(int Idx, out LocalClientInfo _localClientInfo)
// {
// if (!DictIdx2LocalClientInfo.ContainsKey(Idx))
// {
// _localClientInfo = null;
// return false;
// }
public void SetRemoteConnectd(int Idx,bool bConnected)
{
if (!GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
return;
if (bConnected)
AppNoSugarNet.log.Info("远端本地连接已连接!!!!");
else
AppNoSugarNet.log.Info("远端本地连接已断开连接!!!!");
_localClientInfo.bRemoteConnect = bConnected;
}
// _localClientInfo = DictIdx2LocalClientInfo[Idx];
// return true;
// }
public void StopAll()
{
lock (DictIdx2LocalClientInfo)
{
int[] Idxs = DictIdx2LocalClientInfo.Keys.ToArray();
for (int i = 0; i < Idxs.Length; i++)
{
CloseConnectByIdx((byte)Idxs[i]);
}
DictIdx2LocalClientInfo.Clear();
}
}
// public bool GetSocketIdxBySocket(Socket _socket, out int Idx)
// {
// if (_socket == null)
// {
// Idx = -1;
// return false;
// }
#endregion
// if (!DictSocketHandle2Idx.ContainsKey(_socket.Handle))
// {
// Idx = -1;
// return false;
// }
#region
public void EnqueueIdxWithMsg(byte Idx, byte[] data)
{
if (!GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
return;
// Idx = DictSocketHandle2Idx[_socket.Handle];
// return true;
// }
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;
}
// public bool CheckRemoteConnect(int Idx)
// {
// if (!GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
// return false;
// return _localClientInfo.bRemoteConnect;
// }
MsgList = new List<IdxWithMsg>();
lock (_localClientInfo.msgQueue)
{
while (_localClientInfo.msgQueue.Count > 0)
{
IdxWithMsg msg = _localClientInfo.msgQueue.Dequeue();
MsgList.Add(msg);
}
return true;
}
}
#endregion
}
}
// public void SetRemoteConnectd(int Idx,bool bConnected)
// {
// if (!GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
// return;
// if (bConnected)
// AppNoSugarNet.log.Info("远端本地连接已连接!!!!");
// else
// AppNoSugarNet.log.Info("远端本地连接已断开连接!!!!");
// _localClientInfo.bRemoteConnect = bConnected;
// }
// public void StopAllLocalClient()
// {
// lock (DictIdx2LocalClientInfo)
// {
// int[] Idxs = DictIdx2LocalClientInfo.Keys.ToArray();
// for (int i = 0; i < Idxs.Length; i++)
// {
// CloseConnectByIdx((byte)Idxs[i]);
// }
// DictIdx2LocalClientInfo.Clear();
// DictSocketHandle2Idx.Clear();
// ResetFree();
// //清理事件
// OnClientNumberChange -= ClientNumberChange;
// OnReceive -= ReceiveData;
// OnDisconnected -= OnDisconnect;
// OnNetLog -= OnShowNetLog;
// }
// }
// #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);
// }
// return true;
// }
// }
// #endregion
// }
//}

View File

@ -1,292 +1,296 @@
using HaoYueNet.ClientNetworkNet.Standard2.OtherMode;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
//using HaoYueNet.ClientNetwork.OtherMode;
//using HaoYueNet.ServerNetwork;
//using System.Net.Sockets;
namespace NoSugarNet.ClientCoreNet.Standard2
{
public class LocalListener_Source : NetworkHelperCore_ListenerMode
{
public byte mTunnelID;
public long mReciveAllLenght;
public long mSendAllLenght;
public LocalListener_Source(int numConnections, int receiveBufferSize, byte TunnelID)
: base()
{
OnConnected += ClientNumberChange;
OnReceive += ReceiveData;
OnDisconnected += OnDisconnectClient;
OnNetLog += OnShowNetLog;
//namespace NoSugarNet.ClientCore
//{
// public class LocalListener_Source : NetworkHelperCore_ListenerMode
// {
// public byte mTunnelID;
// public long mReciveAllLenght;
// public long mSendAllLenght;
// public LocalListener_Source(int numConnections, int receiveBufferSize, byte TunnelID)
// : base()
// {
// OnConnected += ClientNumberChange;
// OnReceive += ReceiveData;
// OnDisconnected += OnDisconnectClient;
// OnNetLog += OnShowNetLog;
mTunnelID = TunnelID;
}
// mTunnelID = TunnelID;
// }
private void ClientNumberChange(Socket socket)
{
AppNoSugarNet.log.Info("Client数发生变化");
//增加连接数
int Idx = AddDictSocket(socket);
if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInf))
{
AppNoSugarNet.local.OnClientLocalConnect(mTunnelID, (byte)Idx);
}
}
// private void ClientNumberChange(Socket socket)
// {
// AppNoSugarNet.log.Info("Client数发生变化");
// //增加连接数
// int Idx = AddDictSocket(socket);
// if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInf))
// {
// AppNoSugarNet.local.OnClientLocalConnect(mTunnelID, (byte)Idx);
// }
// }
/// <summary>
/// 通过下标发送
/// </summary>
/// <param name="Idx"></param>
/// <param name="data"></param>
public void SendSocketByIdx(int Idx, byte[] data)
{
if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
{
mSendAllLenght += data.Length;
SendToClient(_localClientInfo._socket, data);
}
//TODO连接前缓存数据
}
// /// <summary>
// /// 通过下标发送
// /// </summary>
// /// <param name="Idx"></param>
// /// <param name="data"></param>
// public void SendSocketByIdx(int Idx, byte[] data)
// {
// if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
// {
// mSendAllLenght += data.Length;
// SendToClient(_localClientInfo._socket, data);
// }
// //TODO连接前缓存数据
// }
/// <summary>
/// 接受包回调
/// </summary>
/// <param name="CMDID">协议ID</param>
/// <param name="ERRCODE">错误编号</param>
/// <param name="data">业务数据</param>
private void ReceiveData(Socket sk, byte[] data)
{
DataCallBack(sk, data);
}
// /// <summary>
// /// 接受包回调
// /// </summary>
// /// <param name="CMDID">协议ID</param>
// /// <param name="ERRCODE">错误编号</param>
// /// <param name="data">业务数据</param>
// private void ReceiveData(Socket sk, byte[] data)
// {
// DataCallBack(sk, data);
// }
public void DataCallBack(Socket sk, byte[] data)
{
//AppNoSugarNet.log.Info("收到消息 数据长度=>" + data.Length);
//记录接受长度
mReciveAllLenght += data.Length;
if (!GetSocketIdxBySocket(sk, out int Idx))
return;
try
{
if (GetMsgQueueByIdx(sk.Handle, out Queue<byte[]> _queue))
{
lock (_queue)
{
_queue.Enqueue(data);
while (_queue.Count > 0)
{
AppNoSugarNet.local.OnClientTunnelDataCallBack(mTunnelID, (byte)Idx, _queue.Dequeue());
}
}
}
// public void DataCallBack(Socket sk, byte[] data)
// {
// //AppNoSugarNet.log.Info("收到消息 数据长度=>" + data.Length);
// //记录接受长度
// mReciveAllLenght += data.Length;
// if (!GetSocketIdxBySocket(sk, out int Idx))
// return;
// try
// {
// if (GetMsgQueueByIdx(sk.Handle, out Queue<byte[]> _queue))
// {
// lock (_queue)
// {
// _queue.Enqueue(data);
// while (_queue.Count > 0)
// {
// AppNoSugarNet.local.OnClientTunnelDataCallBack(mTunnelID, (byte)Idx, _queue.Dequeue());
// }
// }
// }
////抛出网络数据
//AppNoSugarNet.local.OnClientTunnelDataCallBack(mTunnelID, (byte)Idx, data);
}
catch (Exception ex)
{
AppNoSugarNet.log.Info("逻辑处理错误:" + ex.ToString());
}
}
// ////抛出网络数据
// //AppNoSugarNet.local.OnClientTunnelDataCallBack(mTunnelID, (byte)Idx, data);
// }
// catch (Exception ex)
// {
// AppNoSugarNet.log.Info("逻辑处理错误:" + ex.ToString());
// }
// }
public void CloseConnectByIdx(byte Idx)
{
if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInf))
{
_localClientInf._socket.Shutdown(SocketShutdown.Both);
}
}
// public void CloseConnectByIdx(byte Idx)
// {
// if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInf))
// {
// _localClientInf._socket.Shutdown(SocketShutdown.Both);
// }
// }
/// <summary>
/// 断开连接
/// </summary>
/// <param name="sk"></param>
public void OnDisconnectClient(Socket sk)
{
AppNoSugarNet.log.Info("断开连接");
// /// <summary>
// /// 断开连接
// /// </summary>
// /// <param name="sk"></param>
// public void OnDisconnectClient(Socket sk)
// {
// AppNoSugarNet.log.Info("断开连接");
if (!GetSocketIdxBySocket(sk, out int Idx))
return;
// if (!GetSocketIdxBySocket(sk, out int Idx))
// return;
AppNoSugarNet.local.OnClientLocalDisconnect(mTunnelID, (byte)Idx);
RemoveDictSocket(sk);
}
// AppNoSugarNet.local.OnClientLocalDisconnect(mTunnelID, (byte)Idx);
// RemoveDictSocket(sk);
// }
public void OnShowNetLog(string msg)
{
AppNoSugarNet.log.Info(msg);
}
// public void OnShowNetLog(string msg)
// {
// AppNoSugarNet.log.Info(msg);
// }
#region
Dictionary<IntPtr, int> DictSocketHandle2Idx = new Dictionary<IntPtr, int>();
Dictionary<IntPtr, Queue<byte[]>> DictSocketHandle2Msg = new Dictionary<IntPtr, Queue<byte[]>>();
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>();
}
// #region 一个轻量级无用户连接管理
// Dictionary<IntPtr, int> DictSocketHandle2Idx = new Dictionary<IntPtr, int>();
// Dictionary<IntPtr, Queue<byte[]>> DictSocketHandle2Msg = new Dictionary<IntPtr, Queue<byte[]>>();
// 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)
{
int Idx = FreeIdxs[0];
FreeIdxs.RemoveAt(0);
return Idx;
}
return mSeedIdx++;
}
// int GetNextIdx()
// {
// if (FreeIdxs.Count > 0)
// {
// int Idx = FreeIdxs[0];
// FreeIdxs.RemoveAt(0);
// return Idx;
// }
// return mSeedIdx++;
// }
/// <summary>
/// 追加Socket返回下标
/// </summary>
/// <param name="socket"></param>
/// <returns></returns>
public int AddDictSocket(Socket socket)
{
if (socket == null)
return -1;
lock (DictSocketHandle2Idx)
{
int Idx = GetNextIdx();
DictSocketHandle2Idx[socket.Handle] = Idx;
DictIdx2LocalClientInfo[Idx] = new LocalClientInfo() { _socket = socket,bRemoteConnect = false};
DictSocketHandle2Msg[socket.Handle] = new Queue<byte[]>();
return Idx;
}
}
// /// <summary>
// /// 追加Socket返回下标
// /// </summary>
// /// <param name="socket"></param>
// /// <returns></returns>
// public int AddDictSocket(Socket socket)
// {
// if (socket == null)
// return -1;
public void RemoveDictSocket(Socket socket)
{
if (socket == null)
return;
lock (DictSocketHandle2Idx)
{
if (!DictSocketHandle2Idx.ContainsKey(socket.Handle))
return;
int Idx = DictSocketHandle2Idx[socket.Handle];
FreeIdxs.Add(Idx);
if (DictIdx2LocalClientInfo.ContainsKey(Idx))
DictIdx2LocalClientInfo.Remove(Idx);
// lock (DictSocketHandle2Idx)
// {
// int Idx = GetNextIdx();
// DictSocketHandle2Idx[socket.Handle] = Idx;
// DictIdx2LocalClientInfo[Idx] = new LocalClientInfo() { _socket = socket,bRemoteConnect = false};
// DictSocketHandle2Msg[socket.Handle] = new Queue<byte[]>();
// AppNoSugarNet.log.Debug($"AddDictSocket mTunnelID->{mTunnelID} Idx->{Idx} socket.Handle{socket.Handle}");
// return Idx;
// }
// }
// public void RemoveDictSocket(Socket socket)
// {
// if (socket == null)
// return;
// lock (DictSocketHandle2Idx)
// {
// if (!DictSocketHandle2Idx.ContainsKey(socket.Handle))
// return;
// int Idx = DictSocketHandle2Idx[socket.Handle];
// FreeIdxs.Add(Idx);
// if (DictIdx2LocalClientInfo.ContainsKey(Idx))
// DictIdx2LocalClientInfo.Remove(Idx);
if (DictSocketHandle2Msg.ContainsKey(socket.Handle))
DictSocketHandle2Msg.Remove(socket.Handle);
// if (DictSocketHandle2Msg.ContainsKey(socket.Handle))
// DictSocketHandle2Msg.Remove(socket.Handle);
DictSocketHandle2Idx.Remove(socket.Handle);
}
}
// DictSocketHandle2Idx.Remove(socket.Handle);
bool GetSocketByIdx(int Idx, out LocalClientInfo _localClientInfo)
{
if (!DictIdx2LocalClientInfo.ContainsKey(Idx))
{
_localClientInfo = null;
return false;
}
// AppNoSugarNet.log.Debug($"RemoveDictSocket mTunnelID->{mTunnelID} Idx->{Idx} socket.Handle{socket.Handle}");
// }
// }
_localClientInfo = DictIdx2LocalClientInfo[Idx];
return true;
}
// bool GetSocketByIdx(int Idx, out LocalClientInfo _localClientInfo)
// {
// if (!DictIdx2LocalClientInfo.ContainsKey(Idx))
// {
// _localClientInfo = null;
// return false;
// }
bool GetMsgQueueByIdx(IntPtr handle, out Queue<byte[]> _queue)
{
if (!DictSocketHandle2Msg.ContainsKey(handle))
{
_queue = null;
return false;
}
// _localClientInfo = DictIdx2LocalClientInfo[Idx];
// return true;
// }
_queue = DictSocketHandle2Msg[handle];
return true;
}
// bool GetMsgQueueByIdx(IntPtr handle, out Queue<byte[]> _queue)
// {
// if (!DictSocketHandle2Msg.ContainsKey(handle))
// {
// _queue = null;
// return false;
// }
public bool GetSocketIdxBySocket(Socket _socket, out int Idx)
{
if (_socket == null)
{
Idx = -1;
return false;
}
// _queue = DictSocketHandle2Msg[handle];
// return true;
// }
if (!DictSocketHandle2Idx.ContainsKey(_socket.Handle))
{
Idx = -1;
return false;
}
// public bool GetSocketIdxBySocket(Socket _socket, out int Idx)
// {
// if (_socket == null)
// {
// Idx = -1;
// return false;
// }
Idx = DictSocketHandle2Idx[_socket.Handle];
return true;
}
// if (!DictSocketHandle2Idx.ContainsKey(_socket.Handle))
// {
// Idx = -1;
// return false;
// }
public bool CheckRemoteConnect(int Idx)
{
if (!GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
return false;
return _localClientInfo.bRemoteConnect;
}
// Idx = DictSocketHandle2Idx[_socket.Handle];
// return true;
// }
public void SetRemoteConnectd(int Idx,bool bConnected)
{
if (!GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
return;
if (bConnected)
AppNoSugarNet.log.Info("远端本地连接已连接!!!!");
else
AppNoSugarNet.log.Info("远端本地连接已断开连接!!!!");
_localClientInfo.bRemoteConnect = bConnected;
}
// public bool CheckRemoteConnect(int Idx)
// {
// if (!GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
// return false;
// return _localClientInfo.bRemoteConnect;
// }
public void StopAll()
{
lock (DictIdx2LocalClientInfo)
{
int[] Idxs = DictIdx2LocalClientInfo.Keys.ToArray();
for (int i = 0; i < Idxs.Length; i++)
{
CloseConnectByIdx((byte)Idxs[i]);
}
DictIdx2LocalClientInfo.Clear();
}
}
// public void SetRemoteConnectd(int Idx,bool bConnected)
// {
// if (!GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
// return;
// if (bConnected)
// AppNoSugarNet.log.Info("远端本地连接已连接!!!!");
// else
// AppNoSugarNet.log.Info("远端本地连接已断开连接!!!!");
// _localClientInfo.bRemoteConnect = bConnected;
// }
#endregion
// public void StopAll()
// {
// lock (DictIdx2LocalClientInfo)
// {
// int[] Idxs = DictIdx2LocalClientInfo.Keys.ToArray();
// for (int i = 0; i < Idxs.Length; i++)
// {
// CloseConnectByIdx((byte)Idxs[i]);
// }
// DictIdx2LocalClientInfo.Clear();
// FreeIdxs.Clear();
// mSeedIdx = 0;
// }
// }
// #endregion
#region
public void EnqueueIdxWithMsg(byte Idx, byte[] data)
{
if (!GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
return;
// #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;
}
// 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);
}
return true;
}
}
#endregion
}
}
// MsgList = new List<IdxWithMsg>();
// lock (_localClientInfo.msgQueue)
// {
// while (_localClientInfo.msgQueue.Count > 0)
// {
// IdxWithMsg msg = _localClientInfo.msgQueue.Dequeue();
// MsgList.Add(msg);
// }
// return true;
// }
// }
// #endregion
// }
//}

View File

@ -1,55 +1,53 @@
using System.Collections.Generic;
//namespace NoSugarNet.ClientCore
//{
// public class IdxWithMsg
// {
// public byte Idx;
// public byte[] data;
// }
namespace NoSugarNet.ClientCoreNet.Standard2
{
public class IdxWithMsg
{
public byte Idx;
public byte[] data;
}
// public class LocalMsgQueuePool
// {
// Queue<IdxWithMsg> msg_pool;
public class LocalMsgQueuePool
{
Queue<IdxWithMsg> msg_pool;
// public LocalMsgQueuePool(int capacity)
// {
// msg_pool = new Queue<IdxWithMsg>(capacity);
// }
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);
// }
// }
/// <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();
// }
// }
//移除并返回在 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 int Count
{
get { return msg_pool.Count; }
}
public void Clear()
{
msg_pool.Clear();
}
}
}
// public void Clear()
// {
// msg_pool.Clear();
// }
// }
//}

View File

@ -1,4 +1,4 @@
namespace NoSugarNet.ClientCoreNet.Standard2.Manager
namespace NoSugarNet.ClientCore.Manager
{
public class LogManager
{
@ -44,5 +44,10 @@
{
OnLog?.Invoke((int)logtype, str);
}
public void Log(int logtype, string str)
{
OnLog?.Invoke(logtype, str);
}
}
}

View File

@ -1,6 +1,6 @@
using AxibugProtobuf;
namespace NoSugarNet.ClientCoreNet.Standard2.Manager
namespace NoSugarNet.ClientCore.Manager
{
public class UserDataBase
{
@ -23,10 +23,11 @@ namespace NoSugarNet.ClientCoreNet.Standard2.Manager
public MainUserDataBase userdata { get;private set; } = new MainUserDataBase();
public bool IsLoggedIn => userdata.IsLoggedIn;
public void InitMainUserData(string UName)
public void InitMainUserData(string UName,long UID)
{
userdata.Account = UName;
userdata.IsLoggedIn = true;
userdata.UID = UID;
//以及其他数据初始化
//...
}
@ -49,7 +50,7 @@ namespace NoSugarNet.ClientCoreNet.Standard2.Manager
//如果之前已登录,则重新登录
if (userdata.IsLoggedIn)
{
AppNoSugarNet.login.Login(userdata.Account);
AppNoSugarNet.login.Login();
}
}
}

View File

@ -1,4 +1,4 @@
namespace NoSugarNet.ClientCoreNet.Standard2
namespace NoSugarNet.ClientCore
{
public struct NetStatus
{

View File

@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
namespace NoSugarNet.ClientCoreNet.Standard2.Network
namespace NoSugarNet.ClientCore.Network
{
public class NetMsg

View File

@ -1,8 +1,14 @@
using HaoYueNet.ClientNetworkNet.Standard2;
using AxibugProtobuf;
using Google.Protobuf;
using HaoYueNet.ClientNetwork;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace NoSugarNet.ClientCoreNet.Standard2.Network
namespace NoSugarNet.ClientCore.Network
{
/// <summary>
/// 继承网络库,以支持网络功能
@ -28,7 +34,7 @@ namespace NoSugarNet.ClientCoreNet.Standard2.Network
/// <summary>
/// 是否自动重连
/// </summary>
public bool bAutoReConnect = false;
public bool bAutoReConnect = true;
/// <summary>
/// 重连尝试时间
/// </summary>
@ -39,12 +45,21 @@ namespace NoSugarNet.ClientCoreNet.Standard2.Network
NetworkDeBugLog($"NetworkConnected:{IsConnect}");
if (IsConnect)
{
AppNoSugarNet.login.Login(Guid.NewGuid().ToString());
//从未登录过
if (!AppNoSugarNet.user.IsLoggedIn)
{
//首次登录
AppNoSugarNet.login.Login();
}
}
else
{
//连接失败
NetworkDeBugLog("连接失败!");
//停止所有
AppNoSugarNet.forwardlocal.StopAll();
//自动重连开关
if (bAutoReConnect)
ReConnect();
@ -86,7 +101,8 @@ namespace NoSugarNet.ClientCoreNet.Standard2.Network
NetworkDeBugLog("OnConnectClose");
//停止所有
AppNoSugarNet.local.StopAll();
AppNoSugarNet.forwardlocal.StopAll();
AppNoSugarNet.reverselocal.StopAll(AppNoSugarNet.user.userdata.UID);
//自动重连开关
if (bAutoReConnect)

View File

@ -0,0 +1,113 @@
using HaoYueNet.ClientNetwork.OtherMode;
using System;
namespace NoSugarNet.Adapter
{
/// <summary>
/// 继承网络库,以支持网络功能
/// </summary>
public class BackwardLocalClient : NetworkHelperCore_SourceMode
{
public long mUID;
public byte mTunnelID;
public byte mIdx;
public long mReciveAllLenght;
public long mSendAllLenght;
public delegate void OnBackwardLogOutHandler(int LogLevel, string Msg);
public delegate void OnBackwardConnectHandler(long uid, byte tunnelId, byte Idx, BackwardLocalClient serverLocalClient);
public delegate void OnBackwardDisconnectHandler(long uid, byte tunnelId, byte Idx, BackwardLocalClient serverLocalClient);
public delegate void OnBackwardDataCallBackHandler(long uid, byte tunnelId, byte Idx, byte[] data);
public event OnBackwardLogOutHandler OnBackwardLogOut;
public event OnBackwardConnectHandler OnBackwardConnect;
public event OnBackwardDisconnectHandler OnBackwardDisconnect;
public event OnBackwardDataCallBackHandler OnBackwardDataCallBack;
public BackwardLocalClient(long UID,byte TunnelID, byte Idx)
{
mUID = UID;
mTunnelID = TunnelID;
mIdx = Idx;
//指定接收服务器数据事件
OnReceiveData += GetDataCallBack;
//断开连接
OnClose += OnConnectClose;
OnConnected += NetworkConnected;
//网络库调试信息输出事件,用于打印网络内容
OnLogOut += NetworkDeBugLog;
}
public void BandEvent(
OnBackwardLogOutHandler _OnBackwardLogOut,
OnBackwardConnectHandler _OnConnect,
OnBackwardDisconnectHandler _OnDisconnect,
OnBackwardDataCallBackHandler _OnDataCallBack
)
{
OnBackwardLogOut += _OnBackwardLogOut;
OnBackwardConnect += _OnConnect;
OnBackwardDisconnect += _OnDisconnect;
OnBackwardDataCallBack += _OnDataCallBack;
}
public void NetworkConnected(bool IsConnect)
{
NetworkDeBugLog($"NetworkConnected:{IsConnect}");
if (IsConnect)
{
OnBackwardConnect?.Invoke(mUID, mTunnelID, mIdx, this);
}
else
{
//连接失败
NetworkDeBugLog("连接失败!");
}
}
public void NetworkDeBugLog(string str)
{
OnBackwardLogOut?.Invoke(1 ,"NetCoreDebug >> " + 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
{
//记录接收数据长度
mReciveAllLenght += data.Length;
//抛出网络数据
OnBackwardDataCallBack?.Invoke(mUID, mTunnelID, mIdx, data);
}
catch (Exception ex)
{
NetworkDeBugLog("逻辑处理错误:" + ex.ToString());
}
}
/// <summary>
/// 关闭连接
/// </summary>
void OnConnectClose()
{
NetworkDeBugLog("OnConnectClose");
OnBackwardDisconnect?.Invoke(mUID, mTunnelID,mIdx,this);
}
public void Release()
{
OnBackwardLogOut -= OnBackwardLogOut;
OnBackwardConnect -= OnBackwardConnect;
OnBackwardDisconnect -= OnBackwardDisconnect;
OnBackwardDataCallBack -= OnBackwardDataCallBack;
}
}
}

View File

@ -0,0 +1,94 @@
using System.IO;
using System.IO.Compression;
namespace NoSugarNet.Adapter.DataHelper
{
public enum E_CompressAdapter
{
//不压缩
None = 0,
//GIPZ
GZIP_Plan1 = 1,
}
/// <summary>
/// 压缩适配器
/// </summary>
public class CompressAdapter
{
IDataCompress mIDataCompress;
public CompressAdapter(E_CompressAdapter type)
{
switch (type)
{
//不压缩
case E_CompressAdapter.None:
mIDataCompress = new NoCompress();
break;
//GZIP Plan1
case E_CompressAdapter.GZIP_Plan1:
mIDataCompress = new GZipCompress();
break;
//TODO 其他压缩对比
//……
default:
mIDataCompress = new NoCompress();
break;
}
}
public byte[] Compress(byte[] data)
{
return mIDataCompress.Compress(data);
}
public byte[] Decompress(byte[] data)
{
return mIDataCompress.Decompress(data);
}
}
public interface IDataCompress
{
byte[] Compress(byte[] data);
byte[] Decompress(byte[] data);
}
public class NoCompress : IDataCompress
{
public byte[] Compress(byte[] data)
{
return data;
}
public byte[] Decompress(byte[] data)
{
return data;
}
}
public class GZipCompress : IDataCompress
{
public byte[] Compress(byte[] data)
{
using (var compressedStream = new MemoryStream())
using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
{
zipStream.Write(data, 0, data.Length);
zipStream.Close();
return compressedStream.ToArray();
}
}
public byte[] Decompress(byte[] data)
{
using (var compressedStream = new MemoryStream(data))
using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
using (var resultStream = new MemoryStream())
{
zipStream.CopyTo(resultStream);
return resultStream.ToArray();
}
}
}
}

View File

@ -0,0 +1,19 @@
using NoSugarNet.Adapter.DataHelper;
using System.Collections.Generic;
namespace NoSugarNet.Adapter.DataHelper
{
public static class CompressAdapterSelector
{
static Dictionary<E_CompressAdapter, CompressAdapter> mDictAdapter = new Dictionary<E_CompressAdapter, CompressAdapter>();
public static CompressAdapter Adapter(E_CompressAdapter adptType)
{
if(mDictAdapter.ContainsKey(adptType))
return mDictAdapter[adptType];
mDictAdapter[adptType] = new CompressAdapter(adptType);
return mDictAdapter[adptType];
}
}
}

View File

@ -0,0 +1,347 @@
using HaoYueNet.ServerNetwork.Standard2;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
namespace NoSugarNet.Adapter
{
public class ForwardLocalListener : TcpSaeaServer_SourceMode
{
public byte mTunnelID;
public long mReciveAllLenght;
public long mSendAllLenght;
public long currSeed;
public long mUid;
static long Seed;
public enum AdptLogLevel
{
Debug,
Info,
Warning,
Error
}
public delegate void OnLogOutHandler(int LogLevel,string Msg);
public delegate void OnClientLocalConnectHandler(long UID, byte tunnelId, byte _Idx);
public delegate void OnClientLocalDisconnectHandler(long UID, byte tunnelId, byte _Idx);
public delegate void OnClientTunnelDataCallBackHandler(long UID, byte tunnelId, byte Idx, byte[] data);
public event OnLogOutHandler OnForwardLogOut;
public event OnClientLocalConnectHandler OnClientLocalConnect;
public event OnClientLocalDisconnectHandler OnClientLocalDisconnect;
public event OnClientTunnelDataCallBackHandler OnClientTunnelDataCallBack;
public ForwardLocalListener(int numConnections, int receiveBufferSize, byte TunnelID, long mUid)
: base(numConnections, receiveBufferSize)
{
OnClientNumberChange += ClientNumberChange;
OnReceive += ReceiveData;
OnDisconnected += OnDisconnect;
OnNetLog += OnShowNetLog;
mTunnelID = TunnelID;
currSeed = Seed++;
this.mUid = mUid;
}
public event OnLogOutHandler OnForwardLogOut2;
public void BandEvent(
OnLogOutHandler _OnLogOut,
OnClientLocalConnectHandler _OnClientLocalConnect,
OnClientLocalDisconnectHandler _OnClientLocalDisconnect,
OnClientTunnelDataCallBackHandler _ClientTunnelDataCall
)
{
OnForwardLogOut += _OnLogOut;
OnClientLocalConnect += _OnClientLocalConnect;
OnClientLocalDisconnect += _OnClientLocalDisconnect;
OnClientTunnelDataCallBack += _ClientTunnelDataCall;
}
public void StartListener(uint port)
{
Init();
Start(new IPEndPoint(IPAddress.Any.Address, (int)port));
}
private void ClientNumberChange(int num, AsyncUserToken token)
{
OnForwardLogOut?.Invoke((int)AdptLogLevel.Info, "Client数发生变化");
//增加连接数stsc
if (num > 0)
{
int Idx = AddDictSocket(token.Socket);
if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInf))
{
OnClientLocalConnect?.Invoke(mUid, mTunnelID, (byte)Idx);
}
}
}
/// <summary>
/// 通过下标发送
/// </summary>
/// <param name="Idx"></param>
/// <param name="data"></param>
public void SendSocketByIdx(int Idx, byte[] data)
{
if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
{
mSendAllLenght += data.Length;
SendToSocket(_localClientInfo._socket, data);
}
//TODO连接前缓存数据
}
/// <summary>
/// 接受包回调
/// </summary>
/// <param name="CMDID">协议ID</param>
/// <param name="ERRCODE">错误编号</param>
/// <param name="data">业务数据</param>
private void ReceiveData(AsyncUserToken token, byte[] data)
{
DataCallBack(token.Socket, data);
}
public void DataCallBack(Socket sk, byte[] data)
{
//AppNoSugarNet.log.Info("收到消息 数据长度=>" + data.Length);
//记录接受长度
mReciveAllLenght += data.Length;
if (!GetSocketIdxBySocket(sk, out int Idx))
return;
try
{
//抛出网络数据
OnClientTunnelDataCallBack?.Invoke(mUid, mTunnelID, (byte)Idx, data);
}
catch (Exception ex)
{
OnForwardLogOut?.Invoke((int)AdptLogLevel.Error,"逻辑处理错误:" + ex.ToString());
}
}
public void CloseConnectByIdx(byte Idx)
{
if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
{
//把未发送消息队列回收了
while (_localClientInfo.msgQueue.Count > 0)
{
IdxWithMsg msg = _localClientInfo.msgQueue.Dequeue();
MsgQueuePool._MsgPool.Enqueue(msg);
}
_localClientInfo._socket.Shutdown(SocketShutdown.Both);
}
}
/// <summary>
/// 断开连接
/// </summary>
/// <param name="sk"></param>
public void OnDisconnect(AsyncUserToken token)
{
OnForwardLogOut?.Invoke((int)AdptLogLevel.Info,"断开连接");
if (!GetSocketIdxBySocket(token.Socket, out int Idx))
return;
OnClientLocalDisconnect?.Invoke(mUid, mTunnelID, (byte)Idx);
RemoveDictSocket(token.Socket);
}
public void OnShowNetLog(string msg)
{
OnForwardLogOut?.Invoke((int)AdptLogLevel.Info, msg);
}
#region
Dictionary<IntPtr, int> DictSocketHandle2Idx = new Dictionary<IntPtr, int>();
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>();
}
public Dictionary<int, LocalClientInfo> GetDictIdx2LocalClientInfo()
{
return DictIdx2LocalClientInfo;
}
int GetNextIdx()
{
if (FreeIdxs.Count > 0)
{
int Idx = FreeIdxs[0];
FreeIdxs.RemoveAt(0);
return Idx;
}
return mSeedIdx++;
}
void ResetFree()
{
FreeIdxs.Clear();
mSeedIdx = 0;
}
/// <summary>
/// 追加Socket返回下标
/// </summary>
/// <param name="socket"></param>
/// <returns></returns>
public int AddDictSocket(Socket socket)
{
if (socket == null)
return -1;
lock (DictSocketHandle2Idx)
{
int Idx = GetNextIdx();
DictSocketHandle2Idx[socket.Handle] = Idx;
DictIdx2LocalClientInfo[Idx] = new LocalClientInfo() { _socket = socket,bRemoteConnect = false};
OnForwardLogOut?.Invoke((int)AdptLogLevel.Debug, $"AddDictSocket mTunnelID->{mTunnelID} Idx->{Idx} socket.Handle{socket.Handle}");
return Idx;
}
}
public void RemoveDictSocket(Socket socket)
{
if (socket == null)
return;
lock (DictSocketHandle2Idx)
{
if (!DictSocketHandle2Idx.ContainsKey(socket.Handle))
return;
int Idx = DictSocketHandle2Idx[socket.Handle];
FreeIdxs.Add(Idx);
if (DictIdx2LocalClientInfo.ContainsKey(Idx))
DictIdx2LocalClientInfo.Remove(Idx);
DictSocketHandle2Idx.Remove(socket.Handle);
OnForwardLogOut?.Invoke((int)AdptLogLevel.Debug, $"RemoveDictSocket mTunnelID->{mTunnelID} Idx->{Idx} socket.Handle{socket.Handle}");
}
}
bool GetSocketByIdx(int Idx, out LocalClientInfo _localClientInfo)
{
if (!DictIdx2LocalClientInfo.ContainsKey(Idx))
{
_localClientInfo = null;
return false;
}
_localClientInfo = DictIdx2LocalClientInfo[Idx];
return true;
}
public bool GetSocketIdxBySocket(Socket _socket, out int Idx)
{
if (_socket == null)
{
Idx = -1;
return false;
}
if (!DictSocketHandle2Idx.ContainsKey(_socket.Handle))
{
Idx = -1;
return false;
}
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)
OnForwardLogOut?.Invoke((int)AdptLogLevel.Info,"远端本地连接已连接!!!!");
else
OnForwardLogOut?.Invoke((int)AdptLogLevel.Info, "远端本地连接已断开连接!!!!");
_localClientInfo.bRemoteConnect = bConnected;
}
public void StopAllLocalClient()
{
lock (DictIdx2LocalClientInfo)
{
int[] Idxs = DictIdx2LocalClientInfo.Keys.ToArray();
for (int i = 0; i < Idxs.Length; i++)
{
CloseConnectByIdx((byte)Idxs[i]);
}
DictIdx2LocalClientInfo.Clear();
DictSocketHandle2Idx.Clear();
ResetFree();
}
}
public void StopWithClear()
{
base.Stop();
//清理事件
OnForwardLogOut -= OnForwardLogOut;
OnClientLocalConnect -= OnClientLocalConnect;
OnClientLocalDisconnect -= OnClientLocalDisconnect;
OnClientTunnelDataCallBack -= OnClientTunnelDataCallBack;
}
#endregion
#region
public void EnqueueIdxWithMsg(byte Idx, byte[] data)
{
if (!GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
return;
IdxWithMsg Msg = MsgQueuePool._MsgPool.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);
}
return true;
}
}
#endregion
}
}

View File

@ -0,0 +1,57 @@
using System.Collections.Generic;
namespace NoSugarNet.Adapter
{
public class IdxWithMsg
{
public byte Idx;
public byte[] data;
}
public class MsgQueuePool
{
public static MsgQueuePool _MsgPool = new MsgQueuePool(1000);
Queue<IdxWithMsg> msg_pool;
public MsgQueuePool(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

@ -13,8 +13,8 @@
<Reference Include="Google.Protobuf">
<HintPath>..\Lib\Google.Protobuf.dll</HintPath>
</Reference>
<Reference Include="HaoYueNet.ClientNetworkNet.Standard2">
<HintPath>..\Lib\NetLib_Standard2\HaoYueNet.ClientNetworkNet.Standard2.dll</HintPath>
<Reference Include="HaoYueNet.ClientNetwork.Standard2">
<HintPath>..\Lib\NetLib_Standard2\HaoYueNet.ClientNetwork.Standard2.dll</HintPath>
</Reference>
<Reference Include="HaoYueNet.ServerNetwork.Standard2">
<HintPath>..\Lib\NetLib_Standard2\HaoYueNet.ServerNetwork.Standard2.dll</HintPath>

View File

@ -4,7 +4,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<History>True|2024-04-15T06:51:39.2435225Z;True|2024-04-15T14:51:19.4250865+08:00;True|2024-04-15T14:49:22.9829361+08:00;</History>
<History>True|2024-10-18T08:27:43.7757014Z||;True|2024-10-18T16:15:48.7317736+08:00||;True|2024-10-18T15:37:40.8031046+08:00||;True|2024-10-18T15:36:28.8043094+08:00||;True|2024-04-15T14:51:39.2435225+08:00||;True|2024-04-15T14:51:19.4250865+08:00||;True|2024-04-15T14:49:22.9829361+08:00||;</History>
<LastFailureDetails />
</PropertyGroup>
</Project>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<PublishDir>F:\Sin365\NoSugarNet\Lib\NetLib_Standard2</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<_TargetId>Folder</_TargetId>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<History>True|2024-04-15T06:43:38.1978223Z;True|2024-04-15T14:42:22.9030158+08:00;True|2024-04-15T14:10:55.2191388+08:00;True|2024-04-15T14:07:27.2723988+08:00;False|2024-04-15T14:07:03.8682886+08:00;False|2024-04-15T14:06:57.0680795+08:00;</History>
<LastFailureDetails />
</PropertyGroup>
</Project>

View File

@ -22,7 +22,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NoSugarNet.ServerCli", "Sam
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NetLib_Standard2", "NetLib_Standard2", "{4A660CAE-CD92-411C-9D8E-7CB677DB3C74}"
ProjectSection(SolutionItems) = preProject
Lib\NetLib_Standard2\HaoYueNet.ClientNetworkNet.Standard2.dll = Lib\NetLib_Standard2\HaoYueNet.ClientNetworkNet.Standard2.dll
Lib\NetLib_Standard2\HaoYueNet.ClientNetwork.Standard2.dll = Lib\NetLib_Standard2\HaoYueNet.ClientNetwork.Standard2.dll
Lib\NetLib_Standard2\HaoYueNet.ServerNetwork.Standard2.dll = Lib\NetLib_Standard2\HaoYueNet.ServerNetwork.Standard2.dll
Lib\NetLib_Standard2\NoSugarNet.DataHelper.deps.json = Lib\NetLib_Standard2\NoSugarNet.DataHelper.deps.json
Lib\NetLib_Standard2\NoSugarNet.DataHelper.dll = Lib\NetLib_Standard2\NoSugarNet.DataHelper.dll
@ -31,7 +31,9 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NetLib_Standard2", "NetLib_
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NoSugarNet.ClientCore.Standard2", "NoSugarNet.ClientCore.Standard2\NoSugarNet.ClientCore.Standard2.csproj", "{5DB2B608-6F99-430A-99AC-534410393955}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NoSugarNet.Adapter", "NoSugarNet.Adapter\NoSugarNet.Adapter.csproj", "{961FA85B-B6A7-4F45-8239-9E91315253B4}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NoSugarNet.Adapter", "NoSugarNet.Adapter\NoSugarNet.Adapter.csproj", "{961FA85B-B6A7-4F45-8239-9E91315253B4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NoSugarNet.ClientCli.Standard2", "NoSugarNet.ClientCli.Standard2\NoSugarNet.ClientCli.Standard2.csproj", "{97906C2A-2C93-4C63-A237-A75B6EDA8FA4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -63,6 +65,10 @@ Global
{961FA85B-B6A7-4F45-8239-9E91315253B4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{961FA85B-B6A7-4F45-8239-9E91315253B4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{961FA85B-B6A7-4F45-8239-9E91315253B4}.Release|Any CPU.Build.0 = Release|Any CPU
{97906C2A-2C93-4C63-A237-A75B6EDA8FA4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{97906C2A-2C93-4C63-A237-A75B6EDA8FA4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{97906C2A-2C93-4C63-A237-A75B6EDA8FA4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{97906C2A-2C93-4C63-A237-A75B6EDA8FA4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -71,6 +77,7 @@ Global
{29D76CF3-BF7E-45A5-9957-2CBC0A41B6FB} = {5E65F25A-8B59-4FC7-8582-C6887C3CD0A1}
{65220036-9A81-49FA-A5BC-DA06783D2E52} = {5E65F25A-8B59-4FC7-8582-C6887C3CD0A1}
{4A660CAE-CD92-411C-9D8E-7CB677DB3C74} = {EDA9D3FD-1A72-434D-81F6-B1B420406D20}
{97906C2A-2C93-4C63-A237-A75B6EDA8FA4} = {5E65F25A-8B59-4FC7-8582-C6887C3CD0A1}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {637DC2BB-F9BB-41A2-ADC0-B41B871F66DE}

View File

@ -1,7 +1,6 @@
using NoSugarNet.ClientCoreNet.Standard2;
using NoSugarNet.ClientCore;
using NoSugarNet.ClientCore.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
@ -28,8 +27,7 @@ public class MainUI : MonoBehaviour
btnStop.onClick.AddListener(StopNoSugarNetClient);
AddLog("");
AppNoSugarNet.OnUpdateStatus += OnUpdateStatus;
AppNoSugarNet.Init(OnNoSugarNetLog);
AppNoSugarNet.Init(new System.Collections.Generic.Dictionary<byte, TunnelClientData>(),0, OnNoSugarNetLog);
}
private void OnDisable()

View File

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 1d83e3c67ee8b794c97b5876ece7a16e
guid: 190142f96344cb447afd8a87378fa1df
PluginImporter:
externalObjects: {}
serializedVersion: 2

View File

@ -1,33 +0,0 @@
fileFormatVersion: 2
guid: 324deac494a24a7499801349c7908062
PluginImporter:
externalObjects: {}
serializedVersion: 2
iconMap: {}
executionOrder: {}
defineConstraints: []
isPreloaded: 0
isOverridable: 0
isExplicitlyReferenced: 0
validateReferences: 1
platformData:
- first:
Any:
second:
enabled: 1
settings: {}
- first:
Editor: Editor
second:
enabled: 0
settings:
DefaultValueInitialized: true
- first:
Windows Store Apps: WindowsStoreApps
second:
enabled: 0
settings:
CPU: AnyCPU
userData:
assetBundleName:
assetBundleVariant:

View File

@ -16,6 +16,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\NoSugarNet.ClientCore.Standard2\NoSugarNet.ClientCore.Standard2.csproj" />
<ProjectReference Include="..\..\NoSugarNet.ServerCore\NoSugarNet.ServerCore.csproj" />
</ItemGroup>