新增了.net core版本内网代码,

This commit is contained in:
阳涛 葛
2022-10-19 14:37:22 +08:00
parent 319b6badea
commit 1a605509be
25 changed files with 1336 additions and 0 deletions

44
93_nei_core/Ewide.sln Normal file
View File

@@ -0,0 +1,44 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.1.32421.90
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Getf_Service_Transfer_core_client", "Getf_Service_Transfer_core_client\Getf_Service_Transfer_core_client.csproj", "{F037E01A-741E-490C-91F0-76D97137DFA6}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "WinService", "WinService", "{C7306EA1-E2E7-4560-AC1C-49A1A09AF736}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Getf_Service_Transfer_Client_coreService", "Getf_Service_Transfer_Client_coreService\Getf_Service_Transfer_Client_coreService.csproj", "{4182DC0E-24BB-44B6-AFF6-DFD345DF5144}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Getf_Service_Transfer_Client_Service_HttpHandler", "Getf_Service_Transfer_Client_Service_HttpHandler\Getf_Service_Transfer_Client_Service_HttpHandler.csproj", "{699DDA0D-FFB6-4D4D-BA25-D6E9DA62C689}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F037E01A-741E-490C-91F0-76D97137DFA6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F037E01A-741E-490C-91F0-76D97137DFA6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F037E01A-741E-490C-91F0-76D97137DFA6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F037E01A-741E-490C-91F0-76D97137DFA6}.Release|Any CPU.Build.0 = Release|Any CPU
{4182DC0E-24BB-44B6-AFF6-DFD345DF5144}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4182DC0E-24BB-44B6-AFF6-DFD345DF5144}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4182DC0E-24BB-44B6-AFF6-DFD345DF5144}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4182DC0E-24BB-44B6-AFF6-DFD345DF5144}.Release|Any CPU.Build.0 = Release|Any CPU
{699DDA0D-FFB6-4D4D-BA25-D6E9DA62C689}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{699DDA0D-FFB6-4D4D-BA25-D6E9DA62C689}.Debug|Any CPU.Build.0 = Debug|Any CPU
{699DDA0D-FFB6-4D4D-BA25-D6E9DA62C689}.Release|Any CPU.ActiveCfg = Release|Any CPU
{699DDA0D-FFB6-4D4D-BA25-D6E9DA62C689}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{F037E01A-741E-490C-91F0-76D97137DFA6} = {C7306EA1-E2E7-4560-AC1C-49A1A09AF736}
{4182DC0E-24BB-44B6-AFF6-DFD345DF5144} = {C7306EA1-E2E7-4560-AC1C-49A1A09AF736}
{699DDA0D-FFB6-4D4D-BA25-D6E9DA62C689} = {C7306EA1-E2E7-4560-AC1C-49A1A09AF736}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B2073C2C-0FD3-452B-8047-8134D68E12CE}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Getf_Service_Transfer_Client_coreService\Getf_Service_Transfer_Client_coreService.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,200 @@
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using Getf_Service_Transfer_Client_coreService;
using Getf_Service_Transfer_Client_coreService.Entities;
using Getf_Service_Transfer_Client_coreService.Helpers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Getf_Service_Transfer_Client_Service_HttpHandler.HttpByte
{
public class HttpByteHandler : IDataHandler
{
LogHelper _LogHelper;
public TransInfo HandlerData(TransInfo srcData)
{
var r = new TransInfo();
var action = srcData.Body.Action;
if (String.IsNullOrWhiteSpace(action))
{
r.TransResultInfo = GetResult(-320, "Action(url|method)参数不能为空");
return r;
}
var url = action;
var jsonStr = String.IsNullOrWhiteSpace(srcData.Body.Param) ? "{}" : srcData.Body.Param;
var jObject = JsonConvert.DeserializeObject<JObject>(jsonStr);
var rData = DoRequest(url, jObject, srcData.Data, out string msg, out int htttpStatusCode);
if (rData == null)
{
r.TransResultInfo = new TransResult()
{
Code = htttpStatusCode,
Message = msg
};
return r;
}
r.TransResultInfo = new TransResult()
{
Code = htttpStatusCode,
Message = msg
};
r.Data = rData;
return r;
}
private TransResult GetResult(int code, string message)
{
return new TransResult()
{
Code = code,
Message = message
};
}
public byte[] DoRequest(string url, JObject jObject, byte[] data, out string msg, out int httpStatusCode)
{
try
{
Encoding encoding = new UTF8Encoding(false);
if (jObject["Encoding"] != null)
{
encoding = Encoding.GetEncoding(jObject["Encoding"].Value<string>());
}
var method = "POST";
if (jObject["Method"] != null)
{
method = jObject["Method"].Value<string>();
}
HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
var bodyIndex = GetBodyIndex(data);
var headStr = encoding.GetString(data.Take(bodyIndex).ToArray());
var bodyData = data.Skip(bodyIndex)/*.Select(m => (char)m)*/.ToArray();
SetHead(httpWebRequest, method, headStr);
byte[] r;
if (!"GET".Equals(method, StringComparison.OrdinalIgnoreCase))
{
var requestStream = httpWebRequest.GetRequestStream();
requestStream.Write(bodyData, 0, bodyData.Length);
r = GetResponse(httpWebRequest, encoding);
requestStream.Close();
requestStream.Dispose();
}
else
{
r = GetResponse(httpWebRequest, encoding);
}
msg = String.Empty;
httpStatusCode = 200;
return r;
}
catch (WebException e)
{
using (var stream = e?.Response?.GetResponseStream())
{
httpStatusCode = (int?)((System.Net.HttpWebResponse)(e?.Response))?.StatusCode ?? 500;
if (stream != null)
{
using (StreamReader streamReader = new StreamReader(stream))
{
msg = streamReader.ReadToEnd();
}
}
else
{
msg = e.Message;
}
}
}
catch (Exception e)
{
httpStatusCode = 500;
msg = e.Message;
}
return null;
}
private int GetBodyIndex(byte[] data)
{
var index = -1;
for (int i = 0, c = data.Length; i < c; i++)
{
var elem = data[i];
if (elem == '\r' && i + 3 < data.Length && data[i + 1] == '\n' && data[i + 2] == '\r' && data[i + 3] == '\n')
{
index = i + 4;
break;
}
}
return index;
}
private static PropertyInfo InnerCollectionProperty = typeof(WebHeaderCollection).GetProperty("InnerCollection",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
public static void SetHeaderValue(WebHeaderCollection header, string name, string value)
{
var collection = InnerCollectionProperty.GetValue(header, null) as NameValueCollection;
collection[name] = value;
}
private void SetHead(HttpWebRequest httpWebRequest, string method, string headStr)
{
httpWebRequest.Method = method;
var headStrSplitResult = headStr.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var elem in headStrSplitResult)
{
var keyValue = elem.Split(':');
var name = keyValue[0];
var value = keyValue[1];
if ("Accept-Encoding".Equals(name, StringComparison.OrdinalIgnoreCase))
{
httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip;
}
SetHeaderValue(httpWebRequest.Headers, name, value);
}
/*if ("post".Equals(method, StringComparison.OrdinalIgnoreCase))
{
if (String.IsNullOrWhiteSpace(httpWebRequest.ContentType))
{
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
}
}*/
}
private byte[] GetResponse(HttpWebRequest httpWebRequest, Encoding encoding)
{
var response = httpWebRequest.GetResponse();
response.Headers.ToByteArray();
using (var stream = response.GetResponseStream())
{
using (MemoryStream ms = new MemoryStream())
{
stream.CopyTo(ms);
var r = new List<byte>();
r.AddRange(response.Headers.ToByteArray());
//r.AddRange(encoding.GetBytes("\r\n"));
r.AddRange(ms.ToArray());
return r.ToArray();
}
}
}
}
}

View File

@@ -0,0 +1,64 @@
using Getf_Service_Transfer_Client_coreService.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Getf_Service_Transfer_Client_coreService;
namespace Getf_Service_Transfer_Client_Service_HttpHandler
{
public class HttpDataHandler : IDataHandler
{
public TransInfo HandlerData(TransInfo srcData)
{
var r = new TransInfo();
var action = srcData.Body.Action;
if (String.IsNullOrWhiteSpace(action))
{
r.TransResultInfo = GetResult(-320, "Action(url|method)参数不能为空");
return r;
}
var url = action;
HttpService httpService = new HttpService();
var jsonStr = String.IsNullOrWhiteSpace(srcData.Body.Param) ? "{}" : srcData.Body.Param;
var rData = httpService.DoRequest(url, JsonConvert.DeserializeObject<JObject>(jsonStr), out string msg);
if (rData == null)
{
r.TransResultInfo = new TransResult()
{
Code = -301,
Message = msg
};
return r;
}
if (rData is string)
{
r.TransResultInfo = new TransResult()
{
Code = 0,
Message = (string)rData
};
return r;
}
r.TransResultInfo = new TransResult()
{
Code = 0
};
r.Data = (byte[])rData;
return r;
}
private TransResult GetResult(int code, string message)
{
return new TransResult()
{
Code = code,
Message = message
};
}
}
}

View File

@@ -0,0 +1,63 @@
using Getf_Service_Transfer_Client_coreService;
using Getf_Service_Transfer_Client_coreService.Entities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Getf_Service_Transfer_Client_Service_HttpHandler
{
public class HttpJsonDataHandler : IDataHandler
{
public TransInfo HandlerData(TransInfo srcData)
{
var r = new TransInfo();
var action = srcData.Body.Action;
if (String.IsNullOrWhiteSpace(action))
{
r.TransResultInfo = GetResult(-320, "Action(url|method)参数不能为空");
return r;
}
var url = action;
HttpService httpService = new HttpService();
var jsonStr = String.IsNullOrWhiteSpace(srcData.Body.Param) ? "{}" : srcData.Body.Param;
var rData = httpService.DoRequest(url, JsonConvert.DeserializeObject<JObject>(jsonStr), out string msg);
if (rData == null)
{
r.TransResultInfo = new TransResult()
{
Code = -301,
Message = msg
};
return r;
}
if (rData is string)
{
r.TransResultInfo = new TransResult()
{
Code = 0,
Message = (string)rData
};
return r;
}
r.TransResultInfo = new TransResult()
{
Code = 0
};
r.Data = (byte[])rData;
return r;
}
private TransResult GetResult(int code, string message)
{
return new TransResult()
{
Code = code,
Message = message
};
}
}
}

View File

@@ -0,0 +1,167 @@
using Getf_Service_Transfer_Client_coreService.Helpers;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
namespace Getf_Service_Transfer_Client_Service_HttpHandler
{
public class HttpService
{
LogHelper _LogHelper;
public HttpService()
{
_LogHelper = new LogHelper();
}
public object DoRequest(string url, JObject jObject, out string msg)
{
try
{
HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
var head = jObject["Head"];
Encoding encoding = new UTF8Encoding(false);
if (jObject["Encoding"] != null)
{
encoding = Encoding.GetEncoding(jObject["Encoding"].Value<string>());
}
if (jObject["ContentType"] != null)
{
httpWebRequest.ContentType = jObject["ContentType"].Value<string>();
}
var method = "POST";
if (jObject["Method"] != null)
{
method = jObject["Method"].Value<string>();
}
SetHead(httpWebRequest, method, head);
object r;
if (!"GET".Equals(method, StringComparison.OrdinalIgnoreCase))
{
var requestStream = httpWebRequest.GetRequestStream();
SetRequestStream(httpWebRequest, requestStream, jObject, encoding);
r = GetResponse(httpWebRequest, encoding);
requestStream.Close();
requestStream.Dispose();
}
else
{
r = GetResponse(httpWebRequest, encoding);
}
msg = String.Empty;
return r;
}
catch (WebException e)
{
using (var stream = e?.Response?.GetResponseStream())
{
msg = "http错误(" + (int)(e?.Response as HttpWebResponse)?.StatusCode + ")";
if (stream != null)
{
using (StreamReader streamReader = new StreamReader(stream))
{
msg += streamReader.ReadToEnd();
_LogHelper.Info("请求错误原因为:" + msg);
}
}
else
{
msg += e.Message;
_LogHelper.Info("请求错误原因为:" + msg);
}
}
}
catch (Exception e)
{
msg = e.Message;
_LogHelper.Info("请求错误原因为:" + msg);
}
return null;
}
private static PropertyInfo InnerCollectionProperty = typeof(WebHeaderCollection).GetProperty("InnerCollection",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
public static void SetHeaderValue(WebHeaderCollection header, string name, string value)
{
var collection = InnerCollectionProperty.GetValue(header, null) as NameValueCollection;
collection[name] = value;
}
private void SetHead(HttpWebRequest httpWebRequest, string method, JToken head)
{
httpWebRequest.Method = method;
if (head != null)
{
foreach (JProperty elem in head)
{
var name = elem.Name;
var value = elem.Value.ToString();
SetHeaderValue(httpWebRequest.Headers, name, value);
}
}
if ("post".Equals(method, StringComparison.OrdinalIgnoreCase))
{
if (String.IsNullOrWhiteSpace(httpWebRequest.ContentType))
{
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
}
}
}
private void SetRequestStream(HttpWebRequest httpWebRequest, Stream requestStream, JObject jObject, Encoding encoding)
{
using (var streamWrite = new StreamWriter(requestStream, encoding))
{
var param = jObject["Param"]?.Value<string>() ?? String.Empty;
streamWrite.Write(param);
}
}
private static readonly string[] TextContentTypes = new string[] { "application/json", "text/html" };
private object GetResponse(HttpWebRequest httpWebRequest, Encoding encoding)
{
var response = httpWebRequest.GetResponse();
using (var stream = response.GetResponseStream())
{
if (IsTextContentType(response.ContentType))
{
using (StreamReader streamReader = new StreamReader(stream, encoding))
{
var r = streamReader.ReadToEnd();
return r;
}
}
else
{
using (MemoryStream ms = new MemoryStream())
{
stream.CopyTo(ms);
return ms.ToArray();
}
}
}
}
private bool IsTextContentType(string contentType)
{
if (contentType == null) return true;
contentType = contentType.ToLower();
var list = new string[] { "text/", "application/json", "application/xml" };
return list.Any(m => contentType.Contains(m));
}
}
}

View File

@@ -0,0 +1,226 @@
using Furion;
using Furion.Logging;
using Furion.Logging.Extensions;
using Getf_Service_Transfer_Client_coreService.Entities;
using Getf_Service_Transfer_Client_coreService.Helpers;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SuperSocket.ClientEngine;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading;
namespace Getf_Service_Transfer_Client_coreService
{
public class ClientService : IDisposable
{
private DateTime LastRecvTime = DateTime.Now;
LogHelper _LogHelper = new LogHelper();
private readonly IDataHandler DataHandler;
private TcpClient TcpClient;
private readonly string Ip;
private readonly int Port;
private Thread HeartThread;
private bool IsRetrying;
public ClientService()
{
//var serviceAddressInfo = "21".Split("1");
var serviceAddressInfo = App.Configuration["Target:ServiceAddressInfo"].Split(':');
Ip = serviceAddressInfo[0];
Port = int.Parse(serviceAddressInfo[1]);
//var assemblyInfo = "21".Split("1");
var assemblyInfo = App.Configuration["Target:DataHandlerClassInfo"].Split(',');
DataHandler = Assembly.Load(assemblyInfo[1]).CreateInstance(assemblyInfo[0]) as IDataHandler;
//_LogHelper = new LogHelper();
}
public void Start()
{
StartNewEasyClient();
DoHeart();
}
private void DoDebug()
{
for (var i = 0; i < 5; i++)
{
Thread t = new Thread(() =>
{
while (true)
{
var r = GetRegisterEntity();
r.Head.Type = 4;
r.Data = new byte[100 * 1024 * 1024];
Send(r.ToByte());
Thread.Sleep(100);
}
});
t.Start();
}
}
private void StartNewEasyClient()
{
TcpClient = new TcpClient(Ip, Port, OnDataGeted, OnConnected, OnClosed, OnError);
}
private void OnDataGeted(TransInfo transInfo)
{
LastRecvTime = DateTime.Now;
if (transInfo.Body == null)//心跳包
{
/*//应用已被注册 再试
if (transInfo.TransResultInfo != null && transInfo.TransResultInfo.Code == -210)
{
Reconnect(null, null);
}*/
if (transInfo.TransResultInfo != null && transInfo.TransResultInfo.Message == "注册成功!")
{
"注册成功".LogInformation();
_LogHelper.Info("注册成功");
return;
}
else
{
if (transInfo.TransResultInfo != null && !String.IsNullOrWhiteSpace(transInfo.TransResultInfo.Message))
{
string info = "发生错误:" + transInfo.TransResultInfo.Message;
info.LogError();
_LogHelper.Error("发生错误:" + transInfo.TransResultInfo.Message);
}
}
return;
}
var transResult = DataHandler.HandlerData(transInfo);
var r = GetRegisterEntity();
r.Body = new TransBody()
{
Key = transInfo.Body.Key
};
r.Head.Type = 3;
r.TransResultInfo = transResult.TransResultInfo;
r.Data = transResult.Data;
Send(r.ToByte());
}
private void OnConnected(object sender, EventArgs e)
{
IsRetrying = false;
_LogHelper.Info("连接成功");
"连接成功".LogInformation();
Send(GetRegisterEntity().ToByte());
}
private void OnClosed(object sender, EventArgs e)
{
"EasyClient.OnClosed".LogInformation();
_LogHelper.Info("EasyClient.OnClosed");
ReStart();
}
private void OnError(object sender, EventArgs e)
{
string warn = "连接出错,原因为:" + ((ErrorEventArgs)e).Exception.Message;
warn.LogWarning();
//_LogHelper.Info("连接出错,原因为:" + ((ErrorEventArgs)e).Exception.Message);
ReStart();
}
private void ReStart()
{
Thread.Sleep(5000);
StartNewEasyClient();
}
private void DoHeart()
{
#if DEBUG
/*for (int i = 0; i < 100; i++)
{
var testThread = new Thread(() =>
{
while (true)
{
SendHeart();
}
});
testThread.Start();
}*/
#endif
HeartThread = new Thread(() =>
{
while (true)
{
if ((DateTime.Now - LastRecvTime).TotalMinutes > 10)
{
_LogHelper.Error("超过一分钟没收到心跳包的反馈信息");
TcpClient.HeartLost();
}
if (TcpClient.IsConnected)
{
SendHeart();
}
Thread.Sleep(5 * 1000);
}
});
HeartThread.Start();
}
private void SendHeart()
{
var r = GetRegisterEntity();
r.Head.Type = 4;
Send(r.ToByte());
}
private void Send(byte[] data)
{
if (!TcpClient.IsConnected) return;
try
{
TcpClient.Send(data);
}
catch (Exception e)
{
_LogHelper.Error("发送错误原因为:" + e.Message);
}
}
private TransInfo GetRegisterEntity()
{
var ts = TypeHelper.GetTimeStamp();
var r = new TransInfo()
{
Head = new TransHead()
{
Type = 1,
AppID = App.Configuration["Target:AppID"],
AppSecret = App.Configuration["Target:AppSecret"],
TimeStamp = ts,
Sign = Md5Helper.Md5(ts + App.Configuration["Target:Key"])
}
};
return r;
}
public void Dispose()
{
TcpClient.Dispose();
}
}
}

View File

@@ -0,0 +1,74 @@
using SuperSocket.ProtoBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
namespace Getf_Service_Transfer_Client_coreService.Entities
{
public class ReceiveFilter : FixedHeaderReceiveFilter<TransInfo>
{
public ReceiveFilter() : base(10)
{
}
protected override int GetBodyLengthFromHeader(IBufferStream bufferStream, int length)
{
bufferStream.ReadInt16();
var len = GetStrLength(bufferStream) + GetDataLength(bufferStream);
return len;
}
public override TransInfo ResolvePackage(IBufferStream bufferStream)
{
((Stream)bufferStream).Position = 2;
var strLength = GetStrLength(bufferStream);
var dataLength = GetDataLength(bufferStream);
var allLength = strLength + dataLength;
byte[] buffer = new byte[strLength];
bufferStream.Read(buffer, 0, strLength);
var json = Encoding.UTF8.GetString(buffer);
var r = JsonConvert.DeserializeObject<TransInfo>(json);
if (r == null)
{
return new TransInfo();
}
buffer = new byte[dataLength];
bufferStream.Read(buffer, 0, dataLength);
r.Data = buffer;
return r;
}
/*protected override TransInfo ResolveRequestInfo(ArraySegment<byte> header, byte[] bodyBuffer, int offset, int length)
{
var strLength = BitConverter.ToInt32(header.Array, header.Offset + 2);
var dataLength = BitConverter.ToInt32(header.Array, header.Offset + 6);
var json = Encoding.UTF8.GetString(bodyBuffer.Skip(offset).Take(strLength).ToArray());
var r = JsonConvert.DeserializeObject<TransInfo>(json);
r.Data = bodyBuffer.Skip(offset + strLength).Take(dataLength).ToArray();
return r;
}*/
private int GetStrLength(IBufferStream bufferStream)
{
byte[] buffer = new byte[4];
bufferStream.Read(buffer, 0, 4);
var r = BitConverter.ToInt32(buffer, 0);
return r;
}
private int GetDataLength(IBufferStream bufferStream)
{
byte[] buffer = new byte[4];
bufferStream.Read(buffer, 0, 4);
var r = BitConverter.ToInt32(buffer, 0);
return r;
}
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Getf_Service_Transfer_Client_coreService.Entities
{
public class TransBody
{
public string TargetAppID { get; set; }
public string AppID { get; set; }
public string AppSecret { get; set; }
public string Action { get; set; }
public string Param { get; set; }
public string Key { get; set; }
public string Url { get; set; }
}
}

View File

@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Getf_Service_Transfer_Client_coreService.Entities
{
public class TransHead
{
public string AppID { get; set; }
public string AppSecret { get; set; }
/// <summary>
/// 1 注册 2 请求
/// </summary>
public int Type { get; set; }
public string Param { get; set; }
public string ServiceSecret { get; set; }
public long TimeStamp { get; set; }
public string Sign { get; set; }
}
}

View File

@@ -0,0 +1,53 @@
using Newtonsoft.Json;
using SuperSocket.ProtoBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Getf_Service_Transfer_Client_coreService.Entities
{
public class TransInfo : IPackageInfo
{
public TransHead Head { get; set; }
public TransBody Body { get; set; }
public TransResult TransResultInfo { get; set; }
[JsonIgnore]
public byte[] Data { get; set; }
public static TransInfo Parse(byte[] buffer)
{
var strlength = BitConverter.ToInt32(buffer, 2);
var byteLength = BitConverter.ToInt32(buffer, 6);
var json = Encoding.UTF8.GetString(buffer.Skip(10).Take(strlength).ToArray());
if (json == String.Empty)
{
return null;
}
var r = JsonConvert.DeserializeObject<TransInfo>(json);
r.Data = buffer.Skip(10 + strlength).Take(byteLength).ToArray();
return r;
}
public byte[] ToByte()
{
List<byte> bufferHead = new List<byte>();
bufferHead.AddRange(Encoding.UTF8.GetBytes("@@"));
List<byte> bufferBody = new List<byte>();
var json = JsonConvert.SerializeObject(this);
bufferBody.AddRange(Encoding.UTF8.GetBytes(json));
var strLength = bufferBody.Count;
if (Data != null)
{
bufferBody.AddRange(Data);
}
bufferHead.AddRange(BitConverter.GetBytes(strLength));
bufferHead.AddRange(BitConverter.GetBytes(Data == null ? 0 : Data.Length));
bufferHead.AddRange(bufferBody);
return bufferHead.ToArray();
}
}
}

View File

@@ -0,0 +1,20 @@
using Newtonsoft.Json;
using SuperSocket.ProtoBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Getf_Service_Transfer_Client_coreService.Entities
{
public class TransResult
{
public string Key { get; set; }
public int Code { get; set; }
public string Message { get; set; }
public byte[] Data { get; set; }
}
}

View File

@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Furion" Version="4.6.5" />
<PackageReference Include="log4net" Version="2.0.15" />
<PackageReference Include="Newtonsoft.Json.Bson" Version="1.0.2" />
<PackageReference Include="SuperSocket.ClientEngine" Version="0.10.0" />
<PackageReference Include="SuperSocket.ProtoBase" Version="1.7.0.17" />
</ItemGroup>
<ItemGroup>
<None Update="applicationconfig.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,51 @@
using Furion.Logging.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Getf_Service_Transfer_Client_coreService.Helpers
{
public class LogHelper
{
log4net.ILog MLog;
public LogHelper()
{
MLog = log4net.LogManager.GetLogger("Getf.Transfer.Client");
}
public void Debug(string msg)
{
MLog.Debug(msg);
}
public void Error(string msg)
{
msg.LogError();
MLog.Error(msg);
}
public void Error(Exception exception)
{
exception.Message.LogError();
MLog.Error(exception.Message, exception);
}
public void Info(string msg)
{
msg.LogInformation();
MLog.Info(msg);
}
public void Warn(string msg)
{
msg.LogWarning();
MLog.Warn(msg);
}
}
}

View File

@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Threading.Tasks;
namespace Getf_Service_Transfer_Client_coreService.Helpers
{
public static class Md5Helper
{
public static string Md5(string str)
{
MD5 md5 = MD5.Create();
byte[] data = Encoding.UTF8.GetBytes(str);
data = md5.ComputeHash(data);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sb.Append(data[i].ToString("x2"));
}
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Getf_Service_Transfer_Client_coreService.Helpers
{
public class TypeHelper
{
public static DateTime ToDateTime(long timeStamp)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
DateTime dt = startTime.AddSeconds(timeStamp);
return dt;
}
public static long GetTimeStamp()
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
long t = (long)(DateTime.Now - startTime).TotalSeconds;
return t;
}
}
}

View File

@@ -0,0 +1,14 @@
using Getf_Service_Transfer_Client_coreService.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Getf_Service_Transfer_Client_coreService
{
public interface IDataHandler
{
TransInfo HandlerData(TransInfo srcData);
}
}

View File

@@ -0,0 +1,62 @@
using Getf_Service_Transfer_Client_coreService.Entities;
using Newtonsoft.Json;
using SuperSocket.ClientEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
namespace Getf_Service_Transfer_Client_coreService
{
public class TcpClient: IDisposable
//private Thread SendHeartThread;
{
string Ip { get; set; }
int Port { get; set; }
EasyClient EasyClient;
bool IsHeartLosted = false;
Action<object, EventArgs> OnClosed;
public bool IsConnected { get { return EasyClient.IsConnected; } }
public TcpClient(string ip, int port, Action<TransInfo> onDataGeted, Action<object, EventArgs> onConnected, Action<object, EventArgs> onClosed, Action<object, EventArgs> onError)
{
Ip = ip;
Port = port;
EasyClient = new EasyClient();
EasyClient.Initialize(new ReceiveFilter(), onDataGeted);
EasyClient.Connected += new EventHandler(onConnected);
EasyClient.Closed += EasyClient_Closed;
EasyClient.Error += new EventHandler<ErrorEventArgs>(onError);
EasyClient.ConnectAsync(new IPEndPoint(IPAddress.Parse(Ip), Port));
OnClosed = onClosed;
//SendHeartThread = new Thread();
}
public void Send(byte[] data)
{
EasyClient.Send(data);
}
private void EasyClient_Closed(object sender, EventArgs e)
{
if (IsHeartLosted) return;
OnClosed?.Invoke(sender, e);
}
public void HeartLost()
{
//IsHeartLosted = true;
EasyClient.Close();
}
public void Dispose()
{
HeartLost();
//SendHeartThread.Abort();
}
}
}

View File

@@ -0,0 +1,40 @@
{
"SpecificationDocumentSettings": {
"DocumentTitle": "Ewide",
"DocExpansionState": "None",
"GroupOpenApiInfos": [
{
"Group": "Default",
"Title": "Admin.NET通用权限管理平台",
"Description": "前后端分离架构,开箱即用,紧随前沿技术。<br/>后台.NET5平台基于Furion框架前端基于XiaoNuo生态技术框架的vue版本。<br/><a href='https://dotnetchina.gitee.io/furion/'>Furion框架,让 .NET 开发更简单,更通用,更流行</a><br/><a href='https://gitee.com/xiaonuobase/xiaonuo-vue/'>XiaoNuo前端框架采用Vue2.x + AntDesign Vue pro1.x + Axios</a>",
"Version": "1.0.0"
},
{
"Group": "HouseBusiness",
"Title": "内外网交互",
"Version": "1.0.1"
}
]
},
"Target": {
"ServiceAddressInfo": "127.0.0.1:8111", //目标服务器地址
"DataHandlerClassInfo": "Getf_Service_Transfer_Client_Service_HttpHandler.HttpDataHandler,Getf_Service_Transfer_Client_Service_HttpHandler",
"AppID": "test",
"AppSecret": "b7ybdg482IXFsojQ4feDHf4NaiSLRtFjL7MVI6ysnvjrZ6jikFX74tVZhZKYG23A",
"Key": "TVgSoGYNJrnU7Kg6Csuodh4IdxqZGxpEJAdRlEcTn72KlUgAiHcr7bdxLKFf9pJ6"
},
"Logging": {
"LogLevel": {
"Default": "Information"
// .... appsettings 默认配置
},
"File": {
"FileName": "application.log", // 日志文件完整路径或文件名,推荐 .log 作为拓展名
"Append": true, // 追加到已存在日志文件或覆盖它们
"MinimumLevel": "Information", // 最低日志记录级别
"FileSizeLimitBytes": 0, // 控制每一个日志文件最大存储大小,单位是 B也就是 1024 才等于 1KB默认无限制如果指定了该值那么日志文件大小超出了该配置就会创建新的日志文件新创建的日志文件命名规则文件名+[递增序号].log
"MaxRollingFiles": 0 // 控制最大创建的日志文件数量,默认无限制,配合 FileSizeLimitBytes 使用,如果指定了该值,那么超出该值将从最初日志文件中从头写入覆盖
}
},
"server.urls": "http://*:5025"
}

View File

@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Worker">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<UserSecretsId>dotnet-Getf_Service_Transfer_core_client-A49AB986-D7BC-4882-BAB1-48CAF75741A2</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Systemd" Version="5.0.1" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="5.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Getf_Service_Transfer_Client_coreService\Getf_Service_Transfer_Client_coreService.csproj" />
<ProjectReference Include="..\Getf_Service_Transfer_Client_Service_HttpHandler\Getf_Service_Transfer_Client_Service_HttpHandler.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,51 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Getf_Service_Transfer_core_client
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.Inject()
.ConfigureServices((hostContext, services) =>
{
//根据日志级别输出
services.AddFileLogging("infomation.log", options =>
{
options.WriteFilter = (logMsg) =>
{
return logMsg.LogLevel == LogLevel.Information;
};
});
services.AddFileLogging("error.log", options =>
{
options.WriteFilter = (logMsg) =>
{
return logMsg.LogLevel == LogLevel.Error;
};
});
services.AddFileLogging("warn.log", options =>
{
options.WriteFilter = (logMsg) =>
{
return logMsg.LogLevel == LogLevel.Warning;
};
});
// services.AddHostedService<Worker>();
})
//.UseWindowsService() ///windows部署
.UseSystemd(); //LIUNX部署
}
}

View File

@@ -0,0 +1,11 @@
{
"profiles": {
"Getf_Service_Transfer_core_client": {
"commandName": "Project",
"dotnetRunMessages": "true",
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,33 @@
using Getf_Service_Transfer_Client_coreService;
using Getf_Service_Transfer_Client_coreService.Helpers;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Getf_Service_Transfer_core_client
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
LogHelper _LogHelper;
ClientService _ClientService;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_ClientService = new ClientService();
_ClientService.Start();
//msg.LogInformation();
//_logger.LogInformation("GET Pages.PrivacyModel called.");
}
}
}

View File

@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

View File

@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}