From f119665d2912f761c484844a1eb95c6a816aba83 Mon Sep 17 00:00:00 2001 From: zgf Date: Fri, 11 Aug 2023 15:17:28 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9ETCP=E6=89=A9=E5=B1=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- HHWMS.Web/Areas/Api/ApiController.cs | 4 +- HHWMS.Web/Areas/Api/IWCSController.cs | 16 +- .../System/Controllers/jobs/SendWcsJob.cs | 67 ++ HHWMS.Web/Controllers/HomeController.cs | 34 +- HHWMS.Web/HHWMS.Web.csproj | 12 +- .../Models/Request/Request/Proto_8357.cs | 66 ++ .../Models/Request/Response/ApiJsonResult.cs | 4 +- HHWMS.Web/Support/QuartzService.cs | 1 + HHWMS.Web/TcpHelper/BufferManager.cs | 60 ++ HHWMS.Web/TcpHelper/DevCommuBySocketClient.cs | 247 +++++++ HHWMS.Web/TcpHelper/MySocketAsyncEventArgs.cs | 26 + HHWMS.Web/TcpHelper/RequestHandler.cs | 57 ++ HHWMS.Web/TcpHelper/SerialPortService.cs | 109 +++ HHWMS.Web/TcpHelper/ServerState.cs | 9 + .../TcpHelper/SocketAsyncEventArgsPool.cs | 122 +++ .../TcpHelper/SocketAsyncEventArgsWithId.cs | 66 ++ HHWMS.Web/TcpHelper/SocketClient.cs | 557 ++++++++++++++ HHWMS.Web/TcpHelper/SocketListener.cs | 696 ++++++++++++++++++ HHWMS.Web/TcpHelper/SyncSocketClient.cs | 117 +++ HHWMS.Web/TcpHelper/TcpService.cs | 184 +++++ HHWMS.Web/appsettings.json | 3 +- src/WalkingTec.Mvvm.Core/Models/ActionLog.cs | 7 + src/WalkingTec.Mvvm.Core/WTMContext.cs | 10 +- src/WalkingTec.Mvvm.Mvc/CodeGenVM.cs | 4 +- .../Filters/FrameworkFilter.cs | 11 + .../DataTableTagHelper.cs | 2 +- 26 files changed, 2457 insertions(+), 34 deletions(-) create mode 100644 HHWMS.Web/Areas/System/Controllers/jobs/SendWcsJob.cs create mode 100644 HHWMS.Web/Models/Request/Request/Proto_8357.cs create mode 100644 HHWMS.Web/TcpHelper/BufferManager.cs create mode 100644 HHWMS.Web/TcpHelper/DevCommuBySocketClient.cs create mode 100644 HHWMS.Web/TcpHelper/MySocketAsyncEventArgs.cs create mode 100644 HHWMS.Web/TcpHelper/RequestHandler.cs create mode 100644 HHWMS.Web/TcpHelper/SerialPortService.cs create mode 100644 HHWMS.Web/TcpHelper/ServerState.cs create mode 100644 HHWMS.Web/TcpHelper/SocketAsyncEventArgsPool.cs create mode 100644 HHWMS.Web/TcpHelper/SocketAsyncEventArgsWithId.cs create mode 100644 HHWMS.Web/TcpHelper/SocketClient.cs create mode 100644 HHWMS.Web/TcpHelper/SocketListener.cs create mode 100644 HHWMS.Web/TcpHelper/SyncSocketClient.cs create mode 100644 HHWMS.Web/TcpHelper/TcpService.cs diff --git a/HHWMS.Web/Areas/Api/ApiController.cs b/HHWMS.Web/Areas/Api/ApiController.cs index c5c9661..ab9a85e 100644 --- a/HHWMS.Web/Areas/Api/ApiController.cs +++ b/HHWMS.Web/Areas/Api/ApiController.cs @@ -8,12 +8,12 @@ namespace HHWMS.Web { protected JsonResult ApiResult(object data = null, string msg = "success") { - return new JsonResult(new ApiJsonResult { Data = data, State = true, Status = true, Message = msg }); + return new JsonResult(new ApiJsonResult { Data = data, Success = true, Status = true, Msg = msg }); } protected JsonResult ApiResultError(object data = null, string msg = "faield") { - return new JsonResult(new ApiJsonResult { Data = data, State = false, Status = false, Message = msg }); + return new JsonResult(new ApiJsonResult { Data = data, Success = false, Status = false, Msg = msg }); } } } diff --git a/HHWMS.Web/Areas/Api/IWCSController.cs b/HHWMS.Web/Areas/Api/IWCSController.cs index 90bd8d4..b91b170 100644 --- a/HHWMS.Web/Areas/Api/IWCSController.cs +++ b/HHWMS.Web/Areas/Api/IWCSController.cs @@ -1,12 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; using AutoMapper; using HHWMS.Web.Models; using Microsoft.AspNetCore.Mvc; using WalkingTec.Mvvm.Core; -using WalkingTec.Mvvm.Core.Extensions; -using Z.EntityFramework.Plus; namespace HHWMS.Web { @@ -130,5 +125,16 @@ namespace HHWMS.Web } return ApiResult(); } + + /// + /// 测试 + /// + /// + /// + [HttpPost] + public IActionResult Test(TaskResponse response) + { + return ApiResult(); + } } } diff --git a/HHWMS.Web/Areas/System/Controllers/jobs/SendWcsJob.cs b/HHWMS.Web/Areas/System/Controllers/jobs/SendWcsJob.cs new file mode 100644 index 0000000..e40ea7b --- /dev/null +++ b/HHWMS.Web/Areas/System/Controllers/jobs/SendWcsJob.cs @@ -0,0 +1,67 @@ +using System; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Threading.Tasks; +using HHWMS.Web.Models; +using Quartz; +using WalkingTec.Mvvm.Core; +using WalkingTec.Mvvm.Core.Extensions; +using WalkingTec.Mvvm.Core.Support.Quartz; +using ProtoBuf; +using Newtonsoft.Json; + +namespace HHWMS.Web +{ + //[QuartzRepeat(10,10, true, 30)] + [PersistJobDataAfterExecution] + [DisallowConcurrentExecution] + public class SendWcsJob : WtmJob + { + public override Task Execute(IJobExecutionContext context) + { + try + { + var _unitwork = new UnitWork(Wtm); + + var taskList = _unitwork.Find(x => x.Status == TaskStatusEnum.新建).Take(10); + foreach (var task in taskList) + { + var taskInfo = new TaskInfo + { + TaskId = task.TaskNo, + TaskType = (int)task.TaskType, + ObjId = task.ContainerCode, + StartPos = new CoordPos + { + X = int.Parse(task.FromLocation.Split("-")[2]), + Y = int.Parse(task.FromLocation.Split("-")[1]), + Z = int.Parse(task.FromLocation.Split("-")[3]) + }, + EndPos = new CoordPos + { + X = int.Parse(task.ToLocation.Split("-")[2]), + Y = int.Parse(task.ToLocation.Split("-")[1]), + Z = int.Parse(task.ToLocation.Split("-")[3]) + } + }; + } + #region 更新时间 + var job = _unitwork.FindSingle(x => x.JobName == context.JobDetail.Key.Name); + if (job != null) + { + job.LastFireTime = TimeZoneInfo.ConvertTimeFromUtc(context.FireTimeUtc.DateTime, TimeZoneInfo.Local); + // 只执行一次 没有下次执行时间 + if (context.NextFireTimeUtc != null) + { + job.NextFireTime = TimeZoneInfo.ConvertTimeFromUtc(context.NextFireTimeUtc.Value.DateTime, TimeZoneInfo.Local); + } + _unitwork.Update(job); + } + #endregion + } + catch { } + return Task.CompletedTask; + } + } +} diff --git a/HHWMS.Web/Controllers/HomeController.cs b/HHWMS.Web/Controllers/HomeController.cs index 257ab22..13eb3e1 100644 --- a/HHWMS.Web/Controllers/HomeController.cs +++ b/HHWMS.Web/Controllers/HomeController.cs @@ -153,25 +153,25 @@ namespace HHWMS.Web.Controllers return JsonMore("No Data"); } - [AllowAnonymous] - public github GetGithubInfo() - { - var rv = Wtm.ReadFromCache("githubinfo", () => - { - var s = Wtm.CallAPI("github", "repos/dotnetcore/wtm", 60).Result; - return s.Data; - }, 1800); + //[AllowAnonymous] + //public github GetGithubInfo() + //{ + // var rv = Wtm.ReadFromCache("githubinfo", () => + // { + // var s = Wtm.CallAPI("github", "repos/dotnetcore/wtm", 60).Result; + // return s.Data; + // }, 1800); - return rv; - } + // return rv; + //} - public class github - { - public int stargazers_count { get; set; } - public int forks_count { get; set; } - public int subscribers_count { get; set; } - public int open_issues_count { get; set; } - } + //public class github + //{ + // public int stargazers_count { get; set; } + // public int forks_count { get; set; } + // public int subscribers_count { get; set; } + // public int open_issues_count { get; set; } + //} } diff --git a/HHWMS.Web/HHWMS.Web.csproj b/HHWMS.Web/HHWMS.Web.csproj index 2e8b200..23f559c 100644 --- a/HHWMS.Web/HHWMS.Web.csproj +++ b/HHWMS.Web/HHWMS.Web.csproj @@ -8,7 +8,7 @@ InProcess b42c99ff-8994-49cd-9a66-5b513ed15a0a HHWMS - Copyright © huahengweld.com 2022 + Copyright © WeiHai.com 2022 @@ -16,6 +16,13 @@ + + + + + + + @@ -24,17 +31,18 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/HHWMS.Web/Models/Request/Request/Proto_8357.cs b/HHWMS.Web/Models/Request/Request/Proto_8357.cs new file mode 100644 index 0000000..827b81b --- /dev/null +++ b/HHWMS.Web/Models/Request/Request/Proto_8357.cs @@ -0,0 +1,66 @@ +using System.Collections.Generic; + +namespace HHWMS.Web.Models +{ + public class TaskInfo + { + public string TaskId { get; set; } + public int TaskType { get; set; } + public string ObjId { get; set; } + public CoordPos StartPos { get; set; } + public int StartType { get; set; } + public CoordPos EndPos { get; set; } + public int EndType { get; set; } + } + + public class CoordPos + { + public int X { get; set; } + public int Y { get; set; } + public int Z { get; set; } + } + + public class TaskResponse + { + public string taskId { get; set; } + public int taskType { get; set; } + public string objId { get; set; } + public int resut { get; set; } + } + + /* + * STACK = 1, //码垛机构 + ROBOT = 2, //机械臂 + FORK = 3, //抓手 暂时不用 + STATION = 4, //堆垛机工位 + STK = 5, //堆垛机 + */ + + public class DeviceMonitor + { + /// + /// 设备类型 + /// + public int DevType { get; set; } + + /// + /// 设备号 + /// + public int DevNo { get; set; } + + /// + /// 设备状态 0:空闲 1:忙率 2:错误 + /// + public int DevStatus { get; set; } + + /// + /// 设备模式 1:手动 2:自动 3:配置 4:半自动 + /// + public int DevMode { get; set; } + + /// + /// 料盒号或者料盘号 取决于任务类型 + /// + public List ErrInfo { get; set; } + } +} diff --git a/HHWMS.Web/Models/Request/Response/ApiJsonResult.cs b/HHWMS.Web/Models/Request/Response/ApiJsonResult.cs index 99de288..2236cec 100644 --- a/HHWMS.Web/Models/Request/Response/ApiJsonResult.cs +++ b/HHWMS.Web/Models/Request/Response/ApiJsonResult.cs @@ -10,12 +10,12 @@ namespace HHWMS.Web.Models /// /// State /// - public bool State { get; set; } + public bool Success { get; set; } /// /// Message /// - public string Message { get; set; } + public string Msg { get; set; } /// /// Data diff --git a/HHWMS.Web/Support/QuartzService.cs b/HHWMS.Web/Support/QuartzService.cs index e0bd8bd..cc023a6 100644 --- a/HHWMS.Web/Support/QuartzService.cs +++ b/HHWMS.Web/Support/QuartzService.cs @@ -18,6 +18,7 @@ namespace HHWMS.Web.Support private IScheduler _scheduler; private static Task task_scheduler = StdSchedulerFactory.GetDefaultScheduler(); private static readonly object objlock = new object(); + //public static DevCommuBySocketClient wcsCommuBySocketClient = new DevCommuBySocketClient("192.168.10.235", 3333, 1000); public QuartzService(IServiceProvider sp, GlobalData gd, IDataContext context) { diff --git a/HHWMS.Web/TcpHelper/BufferManager.cs b/HHWMS.Web/TcpHelper/BufferManager.cs new file mode 100644 index 0000000..abcbb47 --- /dev/null +++ b/HHWMS.Web/TcpHelper/BufferManager.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Net.Sockets; + +namespace HHWMS.Web +{ + public sealed class BufferManager : IDisposable + { + private Byte[] buffer; + private Int32 bufferSize; + private Int32 numSize; + private Int32 currentIndex; + private Stack freeIndexPool; + + public BufferManager(Int32 numSize, Int32 bufferSize) + { + this.bufferSize = bufferSize; + this.numSize = numSize; + this.currentIndex = 0; + this.freeIndexPool = new Stack(); + } + + public void FreeBuffer(SocketAsyncEventArgs args) + { + this.freeIndexPool.Push(args.Offset); + args.SetBuffer(null, 0, 0); + } + + public void InitBuffer() + { + this.buffer = new Byte[this.numSize]; + } + + public Boolean SetBuffer(SocketAsyncEventArgs args) + { + if (this.freeIndexPool.Count > 0) + { + args.SetBuffer(this.buffer, this.freeIndexPool.Pop(), this.bufferSize); + } + else + { + if ((this.numSize - this.bufferSize) < this.currentIndex) + { + return false; + } + args.SetBuffer(this.buffer, this.currentIndex, this.bufferSize); + this.currentIndex += this.bufferSize; + } + return true; + } + + public void Dispose() + { + buffer = null; + freeIndexPool = null; + } + } +} diff --git a/HHWMS.Web/TcpHelper/DevCommuBySocketClient.cs b/HHWMS.Web/TcpHelper/DevCommuBySocketClient.cs new file mode 100644 index 0000000..00216ee --- /dev/null +++ b/HHWMS.Web/TcpHelper/DevCommuBySocketClient.cs @@ -0,0 +1,247 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Timers; +using HHWMS.Web.Models; +using ProtoBuf; +namespace HHWMS.Web +{ + public class DevCommuBySocketClient + { + public enum CommuStatus + { + OFFLINE = 0, + READY = 1, + //SENDING = 2, + RECEIVING = 3 + } + public const int SendWordLength = 70; + //用于通讯的Socket对象 + private SocketClient _socketClient; + public ushort SendIndex { get; set; } + public ushort ReadIndex { get; set; } + public void ResetComm() + { + lock (CommuLock) + { + if (DevCommStatus != CommuStatus.OFFLINE) + { + DevCommStatus = CommuStatus.READY; + } + _heartTimer.Stop(); + _heartTimer.Start(); + } + } + public byte[] ExternalSendBuf + { + set + { + if (value != null) + { + lock (CommuLock) + { + + externalData = new byte[value.Length]; + Array.Copy(value, 0, externalData, 0, value.Length); + } + SendLoop(null, null); + _externalSendtimer.Start(); + } + else + { + lock (CommuLock) + { + externalData = null; + } + } + } + } + //外部触发的需要发送的数据缓存 + + public object CommuLock=new object();//通讯锁 + private System.Timers.Timer _heartTimer;//心跳定时器 + private System.Timers.Timer _externalSendtimer;//外部缓存发送定时器 + private int _sendErrCount;//发送失败的次数 + public CommuStatus DevCommStatus { get; set; }//当前问答模式下的状态 + + public delegate void RecMsgHandler(byte[] msg); + public event RecMsgHandler RecMsgEvent; + + public delegate void OrderRespHandler(); + public event OrderRespHandler OrderRespEvent; + private int mtime = 0; + public DevCommuBySocketClient(string ip, int port, int mtime1) + { + DevCommStatus = CommuStatus.OFFLINE; + _socketClient = new SocketClient(ip, port); + _socketClient.StartListenThread += SocketClient_StartListenThread; + _socketClient.OnSended += SocketClient_OnSended; + _socketClient.OnMsgReceived += SocketClient_OnMsgReceived; + _socketClient.ConnectFail += SocketClient_ConnectFail; + _socketClient.Connect(); + + _heartTimer = new System.Timers.Timer(); + _heartTimer.Interval = 5000; + mtime = mtime1; + _heartTimer.Elapsed += new ElapsedEventHandler(HeartBeat); + _heartTimer.Start(); + _externalSendtimer = new System.Timers.Timer + { + Interval = mtime1 + }; + _externalSendtimer.Elapsed += new ElapsedEventHandler(SendLoop); + reConCount = 30; + SendIndex = 1; + + /*MemoryStream ms = new MemoryStream(); + MsgInstance msgInstance = new MsgInstance + { + requestId = "wms1", + srctype = MsgInstance.SourceType.HEART_BEAT, + + timeInfo = DateTime.Now.ToString() + + }; + //序列化 msg + Serializer.Serialize(ms, msgInstance); + ms.Position = 0; + heartBeatData = ms.ToArray();*/ + } + + private int connectFailCount=0; + private void SocketClient_ConnectFail() + { + connectFailCount++; + } + + private uint reConCount; + //接收到数据的事件 + private void SocketClient_OnMsgReceived(byte[] info) + { + lock (CommuLock) + { + if (info!=null) + { + DevCommStatus = CommuStatus.READY; + } + else + { + DevCommStatus = CommuStatus.OFFLINE; + connectFailCount++; + } + } + } + + //发送完成的事件 + private void SocketClient_OnSended(bool successorfalse) + { + lock (CommuLock) + { + if (successorfalse) + { + externalData = null; + DevCommStatus = CommuStatus.READY; + } + else + { + DevCommStatus = CommuStatus.OFFLINE; + connectFailCount++; + _sendErrCount = 0; + } + } + } + + //连接设备成功的事件 + private void SocketClient_StartListenThread() + { + DevCommStatus = CommuStatus.READY; + } + + public bool SendData(byte[] data) + { + if (DevCommStatus == CommuStatus.READY) + { + if (_socketClient.Send(data)) + { + //DevCommStatus = CommuStatus.SENDING; + return true; + } + return false; + } + if (DevCommStatus== CommuStatus.OFFLINE) + { + if (connectFailCount!=0) + { + connectFailCount = 0; + _socketClient.Connect(); + } + return false; + } + else + { + return false; + } + } + bool electry = true; + private byte[] heartBeatData; + private byte[] externalData; + private void HeartBeat(object sender, ElapsedEventArgs e) + { + lock (CommuLock) + { + if (electry) + { + electry = false; + _heartTimer.Interval = mtime; + } + + if (!_externalSendtimer.Enabled && heartBeatData != null)//没有外部指令的情况下发心跳,优先发外部指令 + { + if (SendData(heartBeatData)) + { + + } + else + { + if (++_sendErrCount > reConCount) + { + _socketClient.ReConnect(); + _sendErrCount = 0; + } + } + } + } + } + + private void SendLoop(object sender, ElapsedEventArgs e) + { + lock (CommuLock) + { + if (externalData != null) + { + if (SendData(externalData)) + { + + } + else + { + if (++_sendErrCount > reConCount) + { + _socketClient.ReConnect(); + _sendErrCount = 0; + } + } + } + else + { + _externalSendtimer.Stop(); + } + } + } + + } +} diff --git a/HHWMS.Web/TcpHelper/MySocketAsyncEventArgs.cs b/HHWMS.Web/TcpHelper/MySocketAsyncEventArgs.cs new file mode 100644 index 0000000..404fcc4 --- /dev/null +++ b/HHWMS.Web/TcpHelper/MySocketAsyncEventArgs.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Net.Sockets; + +namespace HHWMS.Web +{ + public sealed class MySocketAsyncEventArgs : SocketAsyncEventArgs + { + private string Property; //读写类型 + + /// + /// 构造方法 + /// + /// 读写操作类型:Receive/Send + public MySocketAsyncEventArgs(string property) + { + this.Property = property; + } + /// + /// 用户标识 + /// + public string UID { get; set; } + } +} diff --git a/HHWMS.Web/TcpHelper/RequestHandler.cs b/HHWMS.Web/TcpHelper/RequestHandler.cs new file mode 100644 index 0000000..7c1755a --- /dev/null +++ b/HHWMS.Web/TcpHelper/RequestHandler.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace HHWMS.Web +{ + public class RequestHandler + { + private string temp = string.Empty; + public string[] GetActualString(string input) + { + return GetActualString(input, null); + } + private string[] GetActualString(string input, List outputList) + { + if (outputList == null) + outputList = new List(); + if (!String.IsNullOrEmpty(temp)) + input = temp + input; + string output = ""; + string pattern = @"(?<=^\[length=)(\d+)(?=\])"; + int length; + if (Regex.IsMatch(input, pattern)) + { + Match m = Regex.Match(input, pattern); + length = Convert.ToInt32(m.Groups[0].Value); + int startIndex = input.IndexOf(']') + 1; + output = input.Substring(startIndex); + if (output.Length == length) + { + outputList.Add(output); + temp = ""; + } + else if (output.Length < length) + { + temp = input; + } + else if (output.Length > length) + { + output = output.Substring(0, length); + outputList.Add(output); + temp = ""; + input = input.Substring(startIndex + length); + GetActualString(input, outputList); + } + } + else + { + temp = input; + outputList.Add(temp); + } + return outputList.ToArray(); + } + } +} diff --git a/HHWMS.Web/TcpHelper/SerialPortService.cs b/HHWMS.Web/TcpHelper/SerialPortService.cs new file mode 100644 index 0000000..e63fb3d --- /dev/null +++ b/HHWMS.Web/TcpHelper/SerialPortService.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.IO.Ports; + +namespace HHWMS.Web +{ + /// + /// 串口通讯服务类 + /// + public class SerialPortService + { + #region 单例实现 + + //private static SerialPortService instance = null; + //private Dictionary _dicSerialPort = null; //保存串口对象的集合 + + //private SerialPortService() + //{ + // if (this._dicSerialPort == null) + // { + // this._dicSerialPort = new Dictionary(); + // } + //} + + //public static SerialPortService Instance + //{ + // get + // { + // if (instance == null) + // { + // instance = new SerialPortService(); + // } + // return instance; + // } + //} + + //#endregion + + //#region 获取串口对象 + + ///// + ///// 获取串口对象 + ///// + ///// 串口名称 + ///// 波特率 + ///// 返可用的串口对象 + //public SerialPort GetSerialPort(string portName, int baudRate) + //{ + // SerialPort currSerialPort = null; + // foreach (SerialPort sp in this._dicSerialPort.Values) + // { + // if (sp.PortName == portName && sp.BaudRate == baudRate) + // { + // currSerialPort = sp; + // break; + // } + // } + // if (currSerialPort == null) + // { + // currSerialPort = new SerialPort(); + // currSerialPort.PortName = portName; + // currSerialPort.BaudRate = baudRate; + + // currSerialPort.ReadTimeout = 3000; + // currSerialPort.Handshake = Handshake.None; + // currSerialPort.ReceivedBytesThreshold = 1; + + // currSerialPort.RtsEnable = true; + + // currSerialPort.Encoding = System.Text.Encoding.Default; + // this._dicSerialPort.Add(currSerialPort.GetHashCode(), currSerialPort); + // } + // try + // { + // if (currSerialPort.IsOpen) + // { + // currSerialPort.Close(); + // currSerialPort.Open(); + // } + // else + // { + // currSerialPort.Open(); + // } + // } + // catch (Exception ex) + // { + // //ICSharpCode.Core.LoggingService.Warn(String.Format("串口{0}关闭或打开失败,重新创建串口对象,详情:{1}", portName, ex.Message)); + // this._dicSerialPort.Remove(currSerialPort.GetHashCode()); + // currSerialPort = new SerialPort(); + // currSerialPort.PortName = portName; + // currSerialPort.BaudRate = baudRate; + + // currSerialPort.ReadTimeout = 3000; + // currSerialPort.Handshake = Handshake.None; + // currSerialPort.ReceivedBytesThreshold = 1; + // currSerialPort.RtsEnable = true; + + // currSerialPort.Encoding = System.Text.Encoding.Default; + // this._dicSerialPort.Add(currSerialPort.GetHashCode(), currSerialPort); + // currSerialPort.Open(); + // } + // return currSerialPort; + //} + + #endregion + } +} diff --git a/HHWMS.Web/TcpHelper/ServerState.cs b/HHWMS.Web/TcpHelper/ServerState.cs new file mode 100644 index 0000000..f1556e7 --- /dev/null +++ b/HHWMS.Web/TcpHelper/ServerState.cs @@ -0,0 +1,9 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace HHWMS.Web +{ + public enum ServerState { Initialing, Inited, Ready, Running, Stoped } +} diff --git a/HHWMS.Web/TcpHelper/SocketAsyncEventArgsPool.cs b/HHWMS.Web/TcpHelper/SocketAsyncEventArgsPool.cs new file mode 100644 index 0000000..7499c12 --- /dev/null +++ b/HHWMS.Web/TcpHelper/SocketAsyncEventArgsPool.cs @@ -0,0 +1,122 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Net.Sockets; + +namespace HHWMS.Web +{ + public sealed class SocketAsyncEventArgsPool : IDisposable + { + private Stack pool; + private IDictionary busypool; + //private string[] keys; + + public Int32 Count + { + get + { + lock (this.pool) + { + return this.pool.Count; + } + } + } + + public string[] OnlineUID + { + get + { + string[] keys = null; + lock (this.busypool) + { + //busypool.Keys.CopyTo(keys, 0); + keys = busypool.Keys.ToArray(); + } + return keys; + } + } + + public Stack Pool { get { return this.pool; } } + + public IDictionary BusyPool { get { return this.busypool; } } + + public SocketAsyncEventArgsPool(Int32 capacity) + { + //keys = new string[capacity]; + this.pool = new Stack(capacity); + this.busypool = new Dictionary(capacity); + } + + public SocketAsyncEventArgsWithId Pop(string uid) + { + if (uid == string.Empty || uid == "") + return null; + SocketAsyncEventArgsWithId si = null; + lock (this.pool) + { + si = this.pool.Pop(); + } + si.UID = uid; + si.State = true; //mark the state of pool is not the initial step + busypool.Add(uid, si); + return si; + } + + public void Push(SocketAsyncEventArgsWithId item) + { + if (item == null) + throw new ArgumentNullException("SocketAsyncEventArgsWithId对象为空"); + if (item.State == true) + { + if (busypool.Keys.Count != 0) + { + if (busypool.Keys.Contains(item.UID)) + busypool.Remove(item.UID); + //else + // throw new ArgumentException("SocketAsyncEventWithId不在忙碌队列中"); + } + else + throw new ArgumentException("忙碌队列为空"); + } + item.UID = "-1"; + item.State = false; + lock (this.pool) + { + this.pool.Push(item); + } + } + + public SocketAsyncEventArgsWithId FindByUID(string uid) + { + if (uid == string.Empty || uid == "") + return null; + SocketAsyncEventArgsWithId si = null; + foreach (string key in this.OnlineUID) + { + if (key == uid) + { + si = busypool[uid]; + break; + } + } + return si; + } + + public bool BusyPoolContains(string uid) + { + lock (this.busypool) + { + return busypool.Keys.Contains(uid); + } + } + + public void Dispose() + { + this.pool.Clear(); + this.busypool.Clear(); + this.pool = null; + this.busypool = null; + } + } +} diff --git a/HHWMS.Web/TcpHelper/SocketAsyncEventArgsWithId.cs b/HHWMS.Web/TcpHelper/SocketAsyncEventArgsWithId.cs new file mode 100644 index 0000000..7953281 --- /dev/null +++ b/HHWMS.Web/TcpHelper/SocketAsyncEventArgsWithId.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace HHWMS.Web +{ + public sealed class SocketAsyncEventArgsWithId : IDisposable + { + private string uid = "-1"; + private bool state = false; + private bool isAllowReceive = true; + private MySocketAsyncEventArgs receiveSaea; + private MySocketAsyncEventArgs sendSaea; + + public SocketAsyncEventArgsWithId() + { + this.receiveSaea = new MySocketAsyncEventArgs("Receive"); + this.sendSaea = new MySocketAsyncEventArgs("Send"); + } + + public string UID + { + get { return uid; } + set + { + uid = value; + receiveSaea.UID = value; + sendSaea.UID = value; + } + } + + public bool State + { + get { return this.state; } + set { this.state = value; } + } + + /// + /// 是否允许接收 + /// + public bool IsAllowReceive + { + get { return this.isAllowReceive; } + set { this.isAllowReceive = value; } + } + + public MySocketAsyncEventArgs ReceiveSAEA + { + get { return this.receiveSaea; } + set { this.receiveSaea = value; } + } + + public MySocketAsyncEventArgs SendSAEA + { + get { return this.sendSaea; } + set { this.sendSaea = value; } + } + + public void Dispose() + { + this.receiveSaea.Dispose(); + this.sendSaea.Dispose(); + } + } +} diff --git a/HHWMS.Web/TcpHelper/SocketClient.cs b/HHWMS.Web/TcpHelper/SocketClient.cs new file mode 100644 index 0000000..ea8576b --- /dev/null +++ b/HHWMS.Web/TcpHelper/SocketClient.cs @@ -0,0 +1,557 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Net; +using System.Net.Sockets; +using System.Configuration; + +namespace HHWMS.Web +{ + /// + /// Socket客户端类,连接App.Config中FeedingIP:Port + /// + public class SocketClient : IDisposable + { + #region 字段、委托、事件 + + //private static SocketClient instance = null; + /// + /// 客户端连接Socket + /// + private Socket clientSocket; + /// + /// 连接状态 + /// + private Boolean connected = false; + /// + /// 连接点 + /// + private IPEndPoint hostEndPoint; + /// + /// 连接信号量 + /// + //private static AutoResetEvent autoConnectEvent = new AutoResetEvent(false); + /// + /// 接受到数据时的委托 + /// + /// + public delegate void ReceiveMsgHandler(byte[] info); + /// + /// 接收到数据时调用的事件 + /// + public event ReceiveMsgHandler OnMsgReceived; + /// + /// 开始监听数据的委托 + /// + public delegate void StartListenHandler(); + /// + /// 开始监听数据的事件 + /// + public event StartListenHandler StartListenThread; + + /// + /// 连接失败的委托 + /// + public delegate void ConnectFailHandler(); + /// + /// 连接失败的事件 + /// + public event ConnectFailHandler ConnectFail; + + /// + /// 发送信息完成的委托 + /// + /// + public delegate void SendCompleted(bool successorfalse); + /// + /// 发送信息完成的事件 + /// + public event SendCompleted OnSended; + /// + /// 监听接收的SocketAsyncEventArgs + /// + private SocketAsyncEventArgs listenerSocketAsyncEventArgs; + /// + /// 心跳时钟 + /// + private System.Timers.Timer _timer = null; + /// + /// SocketServer服务器IP + /// + public string hostName; + /// + /// SocketServer服务器端口号 + /// + public int port; + + #endregion + + #region 属性定义 + + /// + /// SocketServer服务器IP地址 + /// + string _serverIp; + public string ServerIp + { + get + { + return _serverIp; + } + set + { + _serverIp = value; + } + } + /// + /// SocketServer服务器端口号 + /// + /// + string _serverPort; + public string ServerPort + { + get + { + return _serverPort; + } + set + { + _serverPort = value; + } + } + /// + /// 是否处于连接状态,需要通过定时发送心跳信息来驱动连接状态的变化 + /// + public bool IsConnected + { + get + { + if (this.clientSocket == null) + { + return false; + } + return this.clientSocket.Connected; + } + } + + + #endregion + + #region 初始化 + /// + /// 初始化客户端 + /// + /// 服务端地址{IP地址} + /// 端口号 + public SocketClient(string hostName, Int32 port)//String hostName, Int32 port + { + ServerIp = hostName; + ServerPort = port.ToString(); + this.InitHostEndPoint(); + } + /// + /// 初始化HostEndPoint + /// + private void InitHostEndPoint() + { + string hostName = ServerIp; + int port = 0; + int.TryParse(ServerPort, out port); + + IPAddress address = null; + if (!String.IsNullOrEmpty(hostName)) + { + IPAddress.TryParse(hostName, out address); + } + else + { + IPHostEntry host = Dns.GetHostEntry("127.0.0.1"); + IPAddress[] addressList = host.AddressList; + foreach (IPAddress ad in addressList) + { + if (ad.AddressFamily == AddressFamily.InterNetwork) + { + address = ad; + break; + } + } + } + + this.hostEndPoint = new IPEndPoint(address, port); + } + + #endregion + + #region 连接 + + /// + /// 连接服务端 + /// + public void Connect() + { + bool result = false; + this.Disconnect(); + lock (disPoseLock) + { + this.clientSocket = new Socket(this.hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); + SocketAsyncEventArgs connectArgs = new SocketAsyncEventArgs(); + connectArgs.UserToken = this.clientSocket; + connectArgs.RemoteEndPoint = this.hostEndPoint; + connectArgs.Completed += new EventHandler(OnConnect); + result = clientSocket.ConnectAsync(connectArgs); + }//等待连接结果 + //autoConnectEvent.WaitOne(); + } + + /// + /// 重新连接 + /// + /// + public bool ReConnect() + { + try + { + this.Dispose(); + this.Connect(); + return this.connected; + } + catch (Exception ex) + { + //ICSharpCode.Core.LoggingService.Error("网络断开:" + ex.Message, ex); + return false; + } + } + + /// + /// 没有连接对象返回false,否则重连 + /// + /// 返回重连结果 + public bool IsOrNoReConnect() + { + try + { + lock (this) + { + if (this.clientSocket == null) + { + return false; + } + + return this.ReConnect(); + } + } + catch (System.Exception ex) + { + //ICSharpCode.Core.LoggingService.Error("网络已经断开:" + ex.Message); + return false; + } + } + + /// + /// 连接的完成方法 + /// + /// + /// + private void OnConnect(object sender, SocketAsyncEventArgs e) + { + try + { + //autoConnectEvent.Set(); + SocketError errorCode = e.SocketError; + if (errorCode == SocketError.Success) + { + listenerSocketAsyncEventArgs = new SocketAsyncEventArgs(); + byte[] receiveBuffer = new byte[32768]; + listenerSocketAsyncEventArgs.UserToken = clientSocket; + listenerSocketAsyncEventArgs.SetBuffer(receiveBuffer, 0, receiveBuffer.Length); + listenerSocketAsyncEventArgs.Completed += new EventHandler(OnReceive); + StartListenThread += new SocketClient.StartListenHandler(listener_StartListenThread); + StartListenThread(); + } + else + { + //ICSharpCode.Core.LoggingService.Warn(String.Format("连接SocketServer={0}:{1}失败", this.hostEndPoint.Address.ToString(), this.hostEndPoint.Port)); + //throw new SocketException((Int32)errorCode); + e.Dispose(); + this.Dispose(); + ConnectFail(); + } + } + catch (Exception ex) + { + //ICSharpCode.Core.LoggingService.Error(ex.Message); + } + + this.connected = e.SocketError == SocketError.Success; + } + + #endregion + + #region 断开连接 + + /// + /// 断开连接 + /// + public void Disconnect() + { + lock (disPoseLock) + { + if (clientSocket != null) + { + if (clientSocket.Connected) + { + //autoConnectEvent.Close(); + clientSocket.Shutdown(SocketShutdown.Both); + clientSocket.Disconnect(false); + } + StopListenThread(); + //ICSharpCode.Core.LoggingService.Debug("断开连接"); + } + } + } + + #endregion + + #region 心跳 + + #region 启动心跳时钟 + + /// + /// 启动定时器运行服务 + /// + public void StartHeartbeat() + { + if (this._timer == null) + { + this._timer = new System.Timers.Timer(); + this._timer.Interval = 2000; + this._timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed); + this._timer.Start(); + } + } + + #endregion + + #region 停止心跳时钟 + + /// + /// 停止定时器运行服务 + /// + public void StopHeartbeat() + { + if (this._timer != null) + { + this._timer.Stop(); + this._timer.Dispose(); + this._timer = null; + } + } + + #endregion + + protected void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) + { + if (this.connected) + { + //this.Send("0000"); //发送心跳包 + } + else + { + this.ReConnect(); //重新连接 + } + } + + #endregion + + #region 侦听 + + private void listener_StartListenThread() + { + //ICSharpCode.Core.LoggingService.Debug("开始侦听..."); + //receiveThread = new Thread(new ThreadStart(Listen)); + Listen(); + } + + /// + /// 停止监听线程 + /// + public void StopListenThread() + { + try + { + this.StopHeartbeat(); + if (StartListenThread != null) + { + StartListenThread -= new SocketClient.StartListenHandler(listener_StartListenThread); + } + if (this.listenerSocketAsyncEventArgs != null) + { + listenerSocketAsyncEventArgs.Completed -= new EventHandler(OnReceive); + this.listenerSocketAsyncEventArgs.UserToken = null; + this.listenerSocketAsyncEventArgs.Dispose(); + } + } + catch (Exception ex) + { + //ICSharpCode.Core.LoggingService.Error("停止监听线程异常:", ex); + } + } + + /// + /// 开始监听线程的入口函数 + /// + public void Listen() + { + try + { + Socket socket = listenerSocketAsyncEventArgs.UserToken as Socket; + if (socket != null) + { + socket.ReceiveAsync(listenerSocketAsyncEventArgs); + //if (socket.Connected) + //{ + // this.StartHeartbeat(); + //} + } + } + catch (Exception ex) + { + //ICSharpCode.Core.LoggingService.Error("侦听异常!", ex); + } + } + + #endregion + + #region 消息 + + /// + /// 发送信息 + /// + /// + public bool Send(byte[] sendBuffer) + { + if (clientSocket != null && this.connected) + { + SocketAsyncEventArgs senderSocketAsyncEventArgs = new SocketAsyncEventArgs(); + senderSocketAsyncEventArgs.UserToken = this.clientSocket; + senderSocketAsyncEventArgs.SetBuffer(sendBuffer, 0, sendBuffer.Length); + senderSocketAsyncEventArgs.RemoteEndPoint = this.hostEndPoint; + senderSocketAsyncEventArgs.Completed += new EventHandler(OnSend); + var result = clientSocket.SendAsync(senderSocketAsyncEventArgs); + return true; + } + else + { + //throw new SocketException((Int32)SocketError.NotConnected); + //ICSharpCode.Core.LoggingService.Warn("Socket未初始化或未连接!"); + return false; + } + } + + + /// + /// 接收的完成方法 + /// + /// + /// + private void OnReceive(object sender, SocketAsyncEventArgs e) + { + try + { + if (e.BytesTransferred > 0) + { + byte[] msg = new byte[e.BytesTransferred]; + Array.Copy(e.Buffer, 0, msg, 0, e.BytesTransferred); + //string msg = Encoding.Default.GetString(e.Buffer, 0, e.BytesTransferred); + //ICSharpCode.Core.LoggingService.Debug("接收到数据" + msg); + Listen(); + if (OnMsgReceived != null) + OnMsgReceived(msg); + } + if (e.BytesTransferred==0) + { + this.connected = false; + OnMsgReceived(null); + //ICSharpCode.Core.LoggingService.Debug("server断开连接" + msg); + } + } + catch (Exception ex) + { + //ICSharpCode.Core.LoggingService.Error("接收数据异常:" + ex.Message, ex); + } + } + /// + /// 发送的完成方法 + /// + /// + /// + private void OnSend(object sender, SocketAsyncEventArgs e) + { + if (e.SocketError == SocketError.Success) + { + //触发事件 + if (OnSended != null) + { + OnSended(true); + } + } + else + { + //触发事件 + if (OnSended != null) + { + OnSended(false); + } + this.ProcessError(e); + } + } + /// + /// 处理错误 + /// + /// + private void ProcessError(SocketAsyncEventArgs e) + { + Socket s = e.UserToken as Socket; + if (s != null && s.Connected) + { + try + { + s.Shutdown(SocketShutdown.Both); + } + catch (Exception) + { + //client already closed + } + finally + { + if (s.Connected) + { + s.Close(); + } + } + } + //throw new SocketException((Int32)e.SocketError); + } + + #endregion + + #region IDisposable Members + private object disPoseLock=new object(); + public void Dispose() + { + this.Disconnect(); + lock (disPoseLock) + { + if (clientSocket != null) + { + this.clientSocket.Close(); + this.clientSocket.Dispose(); + this.clientSocket = null; + } + } + } + #endregion + } +} diff --git a/HHWMS.Web/TcpHelper/SocketListener.cs b/HHWMS.Web/TcpHelper/SocketListener.cs new file mode 100644 index 0000000..242f149 --- /dev/null +++ b/HHWMS.Web/TcpHelper/SocketListener.cs @@ -0,0 +1,696 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Net; +using System.Net.Sockets; +using System.Configuration; + +namespace HHWMS.Web +{ + public sealed class SocketListener : IDisposable + { + /// + /// 缓冲区 + /// + private BufferManager bufferManager; + /// + /// 服务器端Socket + /// + private Socket listenSocket; + /// + /// 服务同步锁 + /// + private Mutex mutex; + /// + /// 当前连接数 + /// + private Int32 numConnections; + /// + /// 最大并发量 + /// + private Int32 numConcurrence; + /// + /// 服务器状态 + /// + private ServerState serverstate; + /// + /// 读取写入字节 + /// + private const Int32 opsToPreAlloc = 1; + /// + /// Socket连接池 + /// + private SocketAsyncEventArgsPool readWritePool; + /// + /// 并发控制信号量 + /// + private Semaphore semaphoreAcceptedClients; + /// + /// 通信协议 + /// + private RequestHandler handler; + /// + /// 回调委托 + /// + /// + /// + public delegate string GetIDByIPFun(string IP); + /// + /// 回调方法实例 + /// + private GetIDByIPFun GetIDByIP; + /// + /// 接收到信息时的事件委托 + /// + /// + public delegate void ReceiveMsgHandler(string uid, byte[] info); + /// + /// 接收到信息时的事件 + /// + public event ReceiveMsgHandler OnMsgReceived; + /// + /// 客户端关闭连接时的委托 + /// + /// + public delegate void ClientClose(string uid); + /// + /// 客户端关闭连接时的事件 + /// + public event ClientClose OnClientClose; + /// + /// 开始监听数据的委托 + /// + public delegate void StartListenHandler(); + /// + /// 开始监听数据的事件 + /// + public event StartListenHandler StartListenThread; + /// + /// 发送信息完成后的委托 + /// + /// + public delegate void SendCompletedHandler(string uid, string exception); + /// + /// 发送信息完成后的事件 + /// + public event SendCompletedHandler OnSended; + + private bool listenFlag = false; + + public bool ListenFlag { get { return this.listenFlag; } set { this.listenFlag= value; } } + + /// + /// 获取当前的并发数 + /// + public Int32 NumConnections + { + get { return this.numConnections; } + } + /// + /// 最大并发数 + /// + public Int32 MaxConcurrence + { + get { return this.numConcurrence; } + } + /// + /// 返回服务器状态 + /// + public ServerState State + { + get + { + return serverstate; + } + } + /// + /// 获取当前在线用户的UID + /// + public string[] OnlineUID + { + get { return readWritePool.OnlineUID; } + } + + /// + /// 初始化服务器端 + /// + /// 并发的连接数量(1000以上) + /// 每一个收发缓冲区的大小(32768) + public SocketListener(Int32 numConcurrence, Int32 receiveBufferSize, GetIDByIPFun GetIDByIP) + { + try + { + this.mutex = new Mutex(); + + serverstate = ServerState.Initialing; + this.numConnections = 0; + this.numConcurrence = numConcurrence; + this.bufferManager = new BufferManager(receiveBufferSize * numConcurrence * opsToPreAlloc, receiveBufferSize); + this.readWritePool = new SocketAsyncEventArgsPool(numConcurrence); + this.semaphoreAcceptedClients = new Semaphore(numConcurrence, numConcurrence); + handler = new RequestHandler(); + this.GetIDByIP = GetIDByIP; + } + catch (Exception ex) + { + //ICSharpCode.Core.LoggingService.Error("SocketListener错误:" + ex.Message, ex); + //ICSharpCode.Core.LoggingService.Error(ex.StackTrace); + } + } + + /// + /// 服务端初始化 + /// + public void Init() + { + try + { + this.bufferManager.InitBuffer(); + SocketAsyncEventArgsWithId readWriteEventArgWithId; + for (Int32 i = 0; i < this.numConcurrence; i++) + { + readWriteEventArgWithId = new SocketAsyncEventArgsWithId(); + + readWriteEventArgWithId.SendSAEA.Completed += new EventHandler(OnSendCompleted); + readWriteEventArgWithId.ReceiveSAEA.Completed += new EventHandler(OnReceiveCompleted); + //只给接收的SocketAsyncEventArgs设置缓冲区 + this.bufferManager.SetBuffer(readWriteEventArgWithId.ReceiveSAEA); + this.readWritePool.Push(readWriteEventArgWithId); + } + serverstate = ServerState.Inited; + } + catch (Exception ex) + { + //ICSharpCode.Core.LoggingService.Error("ScoketListner Init错误:" + ex.Message, ex); + //ICSharpCode.Core.LoggingService.Error(ex.StackTrace); + } + } + + /// + /// 启动服务器 + /// + /// 端口号 + public void Start(string ip, Object data) + { + try + { + Int32 port = (Int32)data; + IPAddress[] addresslist = Dns.GetHostEntry(Environment.MachineName).AddressList; + IPAddress ipAddress = addresslist[addresslist.Length - 1]; + if (ip != null) + { + IPAddress.TryParse(ip.ToString(), out ipAddress); + } + IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port); + this.listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); + if (localEndPoint.AddressFamily == AddressFamily.InterNetworkV6) + { + this.listenSocket.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, false); + this.listenSocket.Bind(new IPEndPoint(IPAddress.IPv6Any, localEndPoint.Port)); + } + else + { + this.listenSocket.Bind(localEndPoint); + } + this.listenSocket.Listen(100); + this.StartAccept(null); + //开始监听已连接用户的发送数据 + if (StartListenThread != null) + { + StartListenThread(); + } + serverstate = ServerState.Running; + + mutex.WaitOne(); + } + catch (Exception ex) + { + //ICSharpCode.Core.LoggingService.Error("SocketListner Start错误:" + ex.Message, ex); + //ICSharpCode.Core.LoggingService.Error(ex.StackTrace); + } + } + + /// + /// 开始监听线程的入口函数 + /// + public void Listen() + { + + while (this.listenFlag) + { + lock (readWritePool) + { + string currUser = String.Empty; + try + { + string[] keys = readWritePool.OnlineUID; + foreach (string uid in keys) + { + currUser = uid; + + if (uid != null && readWritePool.BusyPool.ContainsKey(uid) && readWritePool.BusyPool[uid] != null) + { + SocketAsyncEventArgsWithId sawd = readWritePool.BusyPool[uid]; + if (sawd != null || sawd.ReceiveSAEA == null) + { + if (readWritePool.BusyPool[uid].ReceiveSAEA.UID == null) + { + readWritePool.BusyPool[uid].ReceiveSAEA.UID = uid; + } + if ((readWritePool.BusyPool[uid].ReceiveSAEA.UserToken as Socket).Available > 0)// readWritePool.BusyPool[uid].ReceiveSAEA.LastOperation != SocketAsyncOperation.Receive) + { + Boolean willRaiseEvent = (readWritePool.BusyPool[uid].ReceiveSAEA.UserToken as Socket).ReceiveAsync(readWritePool.BusyPool[uid].ReceiveSAEA); + if (!willRaiseEvent) + ProcessReceive(readWritePool.BusyPool[uid].ReceiveSAEA); + } + } + else + { + readWritePool.BusyPool.Remove(uid); + } + #region 注释 + //else if (readWritePool.BusyPool[uid].ReceiveSAEA.LastOperation == SocketAsyncOperation.None) + //{ + // //以下为心跳处理 + // Boolean willRaiseEvent = (readWritePool.BusyPool[uid].ReceiveSAEA.UserToken as Socket).ReceiveAsync(readWritePool.BusyPool[uid].ReceiveSAEA); + //} + //else if (readWritePool.BusyPool[uid].ReceiveSAEA.LastOperation == SocketAsyncOperation.Receive && readWritePool.BusyPool[uid].ReceiveSAEA.SocketError == SocketError.Success) + //{ + // try + // { + // try + // { + // lock (String.Empty) + // { + // if (readWritePool.BusyPool[uid].IsAllowReceive) + // { + // //以下为心跳处理 + // Boolean willRaiseEvent = (readWritePool.BusyPool[uid].ReceiveSAEA.UserToken as Socket).ReceiveAsync(readWritePool.BusyPool[uid].ReceiveSAEA); + // } + // } + // } + // catch (System.InvalidOperationException ex) + // { + // ////ICSharpCode.Core.LoggingService.Error("心跳处理报错无效操作:" + ex.Message); + // //如果产生无效操作异常,说明正常连接,正在接收数据,停止心跳包发送数据 + // if (readWritePool.BusyPool.ContainsKey(uid)) + // { + // readWritePool.BusyPool[uid].IsAllowReceive = false; + // } + // } + // } + // catch (Exception ex) + // { + // //ICSharpCode.Core.LoggingService.Error("心跳处理报错:" + ex.Message); + // //ICSharpCode.Core.LoggingService.Error(ex.StackTrace); + // if (readWritePool.BusyPool.ContainsKey(uid)) + // { + // readWritePool.BusyPool[uid].IsAllowReceive = false; + // } + // } + //} + #endregion + } + + } + + } + catch (Exception ex) + { + //ICSharpCode.Core.LoggingService.Error("监听错误:" + ex.Message, ex); + ////ICSharpCode.Core.LoggingService.Error(ex.StackTrace); + try + { + if (readWritePool.BusyPool.ContainsKey(currUser) && readWritePool.BusyPool[currUser] != null) + { + readWritePool.BusyPool[currUser].Dispose(); + readWritePool.BusyPool.Remove(currUser); + } + else + { + readWritePool.BusyPool.Remove(currUser); + } + Interlocked.Decrement(ref this.numConnections); + //ICSharpCode.Core.LoggingService.Debug("当前连接数:" + this.numConnections); + } + catch { } + } + } + Thread.Sleep(1000); + } + } + + /// + /// 发送信息 + /// + /// 要发送的用户的uid + /// 消息体 + public void Send(string uid, string msg) + { + try + { + + if (uid == string.Empty || uid == "" || msg == string.Empty || msg == "") + return; + SocketAsyncEventArgsWithId socketWithId = readWritePool.FindByUID(uid); + if (socketWithId == null) + //说明用户已经断开 + //100 发送成功 + //200 发送失败 + //300 用户不在线 + //其它 表示异常的信息 + OnSended(uid, "300"); + else + { + MySocketAsyncEventArgs e = socketWithId.SendSAEA; + if (e.SocketError == SocketError.Success) + { + try + { + lock (String.Empty) + { + //string message = @"[lenght=" + msg.Length + @"]" + msg; + string message = msg; + byte[] sendbuffer = System.Text.Encoding.Default.GetBytes(message); + //e.SetBuffer(sendbuffer, 0, sendbuffer.Length); + (e.UserToken as Socket).Send(sendbuffer); + //Boolean willRaiseEvent = (e.UserToken as Socket).SendAsync(e); + //if (!willRaiseEvent) + //{ + // this.ProcessSend(e); + //} + } + } + catch (Exception ex) + { + ////ICSharpCode.Core.LoggingService.Error("Send错误:" + ex.Message, ex); + //if (i <= 5) + //{ + // i++; + // //如果发送出现异常就延迟0.01秒再发 + // Thread.Sleep(10); + // Send(uid, msg); + //} + //else + //{ + // OnSended(uid, ex.ToString()); + //} + OnSended(uid, ex.ToString()); + this.CloseClientSocket(((MySocketAsyncEventArgs)e).UID); + } + } + else + { + OnSended(uid, "200"); + this.CloseClientSocket(((MySocketAsyncEventArgs)e).UID); + } + } + + } + catch (Exception ex) + { + //ICSharpCode.Core.LoggingService.Error("Send错误:" + ex.Message, ex); + //ICSharpCode.Core.LoggingService.Error(ex.StackTrace); + } + } + + /// + /// 停止服务器 + /// + public void Stop() + { + try + { + this.listenFlag = false; + if (listenSocket != null) + listenSocket.Close(); + listenSocket = null; + Dispose(); + try + { + mutex.ReleaseMutex(); + } + catch (ApplicationException ae) + { + //ICSharpCode.Core.LoggingService.Error(ae.Message); + } + serverstate = ServerState.Stoped; + } + catch (Exception ex) + { + //ICSharpCode.Core.LoggingService.Error("SocketListner Stop错误:" + ex.Message, ex); + //ICSharpCode.Core.LoggingService.Error(ex.StackTrace); + } + } + + + private void StartAccept(SocketAsyncEventArgs acceptEventArg) + { + try + { + if (acceptEventArg == null) + { + acceptEventArg = new SocketAsyncEventArgs(); + acceptEventArg.Completed += new EventHandler(OnAcceptCompleted); + } + else + acceptEventArg.AcceptSocket = null; + this.semaphoreAcceptedClients.WaitOne(); + Boolean willRaiseEvent = this.listenSocket.AcceptAsync(acceptEventArg); + if (!willRaiseEvent) + { + this.ProcessAccept(acceptEventArg); + } + } + catch (Exception ex) + { + //ICSharpCode.Core.LoggingService.Error("SocketListener StartAccept错误:" + ex.Message, ex); + //ICSharpCode.Core.LoggingService.Error(ex.StackTrace); + } + } + private void OnAcceptCompleted(object sender, SocketAsyncEventArgs e) + { + this.ProcessAccept(e); + } + private void ProcessAccept(SocketAsyncEventArgs e) + { + if (readWritePool != null) + { + lock (readWritePool) + { + try + { + if (e.LastOperation != SocketAsyncOperation.Accept) //检查上一次操作是否是Accept,不是就返回 + return; + if (this.State == ServerState.Stoped) return; + if (e.AcceptSocket.RemoteEndPoint == null) //服务器断开连接 + return; + IPEndPoint ipEndPoint = e.AcceptSocket.RemoteEndPoint as IPEndPoint; + string UID = GetIDByIP(ipEndPoint.Address.ToString() + ":" + ipEndPoint.Port); //根据IP获取用户的UID + if (UID == string.Empty || UID == null || UID == "") + return; + if (readWritePool.BusyPoolContains(UID)) //判断现在的用户是否已经连接,避免同一用户开两个连接 + { + this.CloseClientSocket(UID); + return; + } + SocketAsyncEventArgsWithId readEventArgsWithId = this.readWritePool.Pop(UID); + + if (readEventArgsWithId.ReceiveSAEA.SocketError != SocketError.Success && readEventArgsWithId.ReceiveSAEA.SocketError != SocketError.ConnectionReset) + { + readEventArgsWithId.ReceiveSAEA.UserToken = null; + readEventArgsWithId.ReceiveSAEA.Dispose(); + readEventArgsWithId.ReceiveSAEA = new MySocketAsyncEventArgs("Receive"); + readEventArgsWithId.ReceiveSAEA.Completed += new EventHandler(OnReceiveCompleted); + + } + if (readEventArgsWithId.SendSAEA.SocketError != SocketError.Success && readEventArgsWithId.SendSAEA.SocketError != SocketError.ConnectionReset) + { + readEventArgsWithId.SendSAEA.UserToken = null; + readEventArgsWithId.SendSAEA.Dispose(); + readEventArgsWithId.SendSAEA = new MySocketAsyncEventArgs("Send"); + readEventArgsWithId.SendSAEA.Completed += new EventHandler(OnSendCompleted); + } + + readEventArgsWithId.ReceiveSAEA.UserToken = e.AcceptSocket; + readEventArgsWithId.SendSAEA.UserToken = e.AcceptSocket; + readEventArgsWithId.IsAllowReceive = true; + Interlocked.Increment(ref this.numConnections); + //Console.WriteLine("当前连接:" + this.numConnections); + //ICSharpCode.Core.LoggingService.Debug("当前连接数:" + this.numConnections); + //触发处理客户端连接完成事件 + if (this.ProcessAcceptComplete != null) + { + this.ProcessAcceptComplete(UID, e); + } + this.StartAccept(e); + } + catch (Exception ex) + { + //ICSharpCode.Core.LoggingService.Error("ProcessAccept错误:" + ex.Message, ex); + //ICSharpCode.Core.LoggingService.Error(ex.StackTrace); + } + } + } + } + + private void OnReceiveCompleted(object sender, SocketAsyncEventArgs e) + { + ProcessReceive(e); + } + private void OnSendCompleted(object sender, SocketAsyncEventArgs e) + { + ////ICSharpCode.Core.LoggingService.Debug("操作类型:" + e.LastOperation); + ProcessSend(e); + } + private void ProcessReceive(SocketAsyncEventArgs e) + { + try + { + lock (String.Empty) + { + if (e.LastOperation != SocketAsyncOperation.Receive) + return; + // 检查如果远程主机关闭了连接 + if (e.BytesTransferred > 0) + { + if (e.SocketError == SocketError.Success) + { + Int32 byteTransferred = e.BytesTransferred; + string received = System.Text.Encoding.Default.GetString(e.Buffer, e.Offset, byteTransferred); + byte[] data = new byte[byteTransferred]; + Array.Copy(e.Buffer, e.Offset, data, 0, byteTransferred); + OnMsgReceived(((MySocketAsyncEventArgs)e).UID, data) ; + //检查消息的准确性 + //string[] msg = handler.GetActualString(received); + //foreach (string m in msg) + // OnMsgReceived(((MySocketAsyncEventArgs)e).UID, m); + try + { + //可以在这里设一个停顿来实现间隔时间段监听,这里的停顿是单个用户间的监听间隔 + //发送一个异步接受请求,并获取请求是否为成功 + Boolean willRaiseEvent = (e.UserToken as Socket).ReceiveAsync(e); + if (!willRaiseEvent) + ProcessReceive(e); + } + catch (System.InvalidOperationException ex) + { + //ProcessReceive(e); + } + } + } + else + this.CloseClientSocket(((MySocketAsyncEventArgs)e).UID); + } + } + catch (Exception ex) + { + //ICSharpCode.Core.LoggingService.Error("ProcessReceive错误:" + ex.Message, ex); + ////ICSharpCode.Core.LoggingService.Error(ex.StackTrace); + } + } + private void ProcessSend(SocketAsyncEventArgs e) + { + try + { + // 检查如果远程主机关闭了连接 + if (e.SocketError == SocketError.Success) + { + if (e.LastOperation != SocketAsyncOperation.Send) + return; + if (e.BytesTransferred > 0) + { + if (e.SocketError == SocketError.Success) + OnSended(((MySocketAsyncEventArgs)e).UID, "100"); + else + OnSended(((MySocketAsyncEventArgs)e).UID, "200"); + } + } + else + { + this.CloseClientSocket(((MySocketAsyncEventArgs)e).UID); + } + } + catch (Exception ex) + { + //ICSharpCode.Core.LoggingService.Error("ProcessSend错误:" + ex.Message, ex); + ////ICSharpCode.Core.LoggingService.Error(ex.StackTrace); + } + } + + private void CloseClientSocket(string uid) + { + if (readWritePool != null) + { + try + { + if (uid == string.Empty || uid == "") + return; + SocketAsyncEventArgsWithId saeaw = readWritePool.FindByUID(uid); + if (saeaw == null) + return; + Socket s = saeaw.ReceiveSAEA.UserToken as Socket; + try + { + s.Shutdown(SocketShutdown.Both); + saeaw.ReceiveSAEA.DisconnectReuseSocket = true; + } + catch (Exception) + { + //客户端已经关闭 + //Console.WriteLine("客户端已经关闭!"); + //ICSharpCode.Core.LoggingService.Warn("客户端已经关闭!"); + } + this.semaphoreAcceptedClients.Release(); + Interlocked.Decrement(ref this.numConnections); + this.readWritePool.Push(saeaw); + //出发事件 + if (this.OnClientClose != null) + { + this.OnClientClose(uid); + } + //Console.WriteLine("当前连接数:" + this.numConnections); + //ICSharpCode.Core.LoggingService.Debug("当前连接数:" + this.numConnections); + } + catch (Exception ex) + { + //ICSharpCode.Core.LoggingService.Error("CloseClientSocket错误:" + ex.Message, ex); + ////ICSharpCode.Core.LoggingService.Error(ex.StackTrace); + } + } + } + + #region IDisposable Members + + public void Dispose() + { + try + { + if (bufferManager != null) + { + bufferManager.Dispose(); + bufferManager = null; + } + if (readWritePool != null) + { + readWritePool.Dispose(); + readWritePool = null; + } + } + catch (Exception ex) + { + //ICSharpCode.Core.LoggingService.Error("Dispose错误:" + ex.Message, ex); + //ICSharpCode.Core.LoggingService.Error(ex.StackTrace); + } + } + + #endregion + + /// + /// 处理接收客户端连接完成事件 + /// + public event EventHandler ProcessAcceptComplete; + } +} diff --git a/HHWMS.Web/TcpHelper/SyncSocketClient.cs b/HHWMS.Web/TcpHelper/SyncSocketClient.cs new file mode 100644 index 0000000..02f9299 --- /dev/null +++ b/HHWMS.Web/TcpHelper/SyncSocketClient.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Net; +using System.Net.Sockets; +using System.Threading; + +namespace HHWMS.Web +{ + public class SyncSocketClient + { + private static SyncSocketClient instance = null; + /// + /// 客户端连接Socket + /// + private Socket clientSocket; + /// + /// 连接点 + /// + private IPEndPoint hostEndPoint; + /// + /// + /// + /// 服务端地址{IP地址} + /// 端口号 + public SyncSocketClient(String hostName, Int32 port) + { + //IPAddress address = null; + //if (!String.IsNullOrEmpty(hostName)) + //{ + // IPAddress.TryParse(hostName, out address); + //} + //else + //{ + // IPHostEntry host = Dns.GetHostEntry(hostName); + // IPAddress[] addressList = host.AddressList; + // foreach (IPAddress ad in addressList) + // { + // if (ad.AddressFamily == AddressFamily.InterNetwork) + // { + // address = ad; + // break; + // } + // } + //} + //this.hostEndPoint = new IPEndPoint(address, port); + //this.clientSocket = new Socket(this.hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); + } + /// + /// 连接服务端 + /// + public string Send(String hostName, Int32 port, string message) + { + + string receiveMsg = ""; + IPAddress address = null; + if (!String.IsNullOrEmpty(hostName)) + { + IPAddress.TryParse(hostName, out address); + } + else + { + IPHostEntry host = Dns.GetHostEntry(hostName); + IPAddress[] addressList = host.AddressList; + foreach (IPAddress ad in addressList) + { + if (ad.AddressFamily == AddressFamily.InterNetwork) + { + address = ad; + break; + } + } + } + IPEndPoint hostPoint = new IPEndPoint(address, port); + using (clientSocket = new Socket(hostPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) + { + + clientSocket.Connect(hostPoint); + clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000); + byte[] sendMsg = Encoding.GetEncoding("GBK").GetBytes(message); + clientSocket.Send(sendMsg); + //设置超时 + //clientSocket.ReceiveTimeout = 5000; + byte[] receiveByte = new byte[1024]; + int count = 0; + try + { + count = clientSocket.Receive(receiveByte, receiveByte.Length, 0);//接受数据 + } + catch (Exception ex) + { + Console.WriteLine(ex.Message + "接受信息超时!"); + } + receiveMsg += Encoding.GetEncoding("GBK").GetString(receiveByte, 0, count);//转换为GBK格式的字符串 + receiveMsg = receiveMsg.Replace("\n\r", ""); + Console.WriteLine("接受信息:" + receiveMsg); + } + return receiveMsg; + } + + /// + /// TCP通信服务实例 + /// + public static SyncSocketClient Instance + { + get + { + if (instance == null) + { + instance = new SyncSocketClient("", 3666); + } + return instance; + } + } + } +} diff --git a/HHWMS.Web/TcpHelper/TcpService.cs b/HHWMS.Web/TcpHelper/TcpService.cs new file mode 100644 index 0000000..2e84235 --- /dev/null +++ b/HHWMS.Web/TcpHelper/TcpService.cs @@ -0,0 +1,184 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Configuration; +using System.Net.Sockets; + +namespace HHWMS.Web +{ + public class TcpService + { + + private SocketListener listener = null; + + private int maxConnection = 100; //允许的最大连接数 + private int bufferSize = 1024 * 1024; //接收缓冲区的大小 + private int port = 3666; //监听的端口号 + private string ip = "127.0.0.1"; //监听的IP地址 + public TcpService(string listenerIp, int port) + { + this.port = port; + this.ip = listenerIp; + + StartService(); + } + + /// + /// 处理客户端连接完成事件 + /// + /// 客户端ip + /// + private void listener_ProcessAcceptComplete(object sender, SocketAsyncEventArgs e) + { + //触发处理客户端连接完成事件 + if (this.ProcessAcceptComplete != null) + { + this.ProcessAcceptComplete(sender, e); + } + } + + private void listener_OnMsgReceived(string uid, byte[] info) + { + if (this.ReceiveMsgHandler != null) + { + this.ReceiveMsgHandler(uid, info); + } + //ICSharpCode.Core.LoggingService.Debug(String.Format("接收到{0}发送的消息:{1}", uid, info)); + } + + private void listener_OnSended(string uid, string exception) + { + if (exception == "100") + { + //ICSharpCode.Core.LoggingService.Debug(String.Format("已发送消息到{0}", uid)); + } + else + { + ////ICSharpCode.Core.LoggingService.Error(String.Format("消息发送错误:{0}", exception)); + //ICSharpCode.Core.LoggingService.Warn("消息发送错误:客户端已经断开连接!"); + } + } + + /// + /// 客户端断开连接的事件处理程序 + /// + /// + private void listener_OnClientClose(string uid) + { + //ICSharpCode.Core.LoggingService.Debug(String.Format("{0}:断开了连接...{1:yyyy-MM-dd HH:mm:ss}", uid, DateTime.Now)); + } + + private void listener_StartListenThread() + { + //ICSharpCode.Core.LoggingService.Debug("开始侦听..."); + ThreadPool.QueueUserWorkItem(new WaitCallback(this.StartListenCallBack), true); + } + + private void StartListenCallBack(object listenFlag) + { + this.listener.ListenFlag = Convert.ToBoolean(listenFlag); + this.listener.Listen(); + } + /// + /// 获取侦听的服务器IP地址 + /// + /// + /// + private string GetIDByIP(string ip) + { + return ip; + } + + /// + /// 启动服务 + /// + private void StartService() + { + try + { + ////ICSharpCode.Core.LoggingService.Debug("最大连接数:" + this.maxConnection); + //ICSharpCode.Core.LoggingService.Debug("侦听的端口号:" + this.port); + this.listener = new SocketListener(this.maxConnection, this.bufferSize, this.GetIDByIP); + this.listener.StartListenThread += new SocketListener.StartListenHandler(listener_StartListenThread); + this.listener.ProcessAcceptComplete += new EventHandler(listener_ProcessAcceptComplete); + this.listener.OnSended += new SocketListener.SendCompletedHandler(listener_OnSended); + this.listener.OnMsgReceived += new SocketListener.ReceiveMsgHandler(listener_OnMsgReceived); + this.listener.OnClientClose += new SocketListener.ClientClose(listener_OnClientClose); + this.listener.Init(); + try + { + this.listener.Start(this.ip, this.port); + } + catch (System.Net.Sockets.SocketException se) + { + if (se.SocketErrorCode == System.Net.Sockets.SocketError.AddressAlreadyInUse) + { + //ICSharpCode.Core.LoggingService.Error(String.Format("端口号{0}已被占用!", this.port)); + } + } + } + catch (Exception ex) + { + //ICSharpCode.Core.LoggingService.Error(ex.Message); + //ICSharpCode.Core.LoggingService.Error(ex.StackTrace); + } + } + /// + /// 重启服务 + /// + public void ReStartService() + { + StopService(); + StartService(); + } + /// + /// 停止服务 + /// + public void StopService() + { + try + { + this.listener.Stop(); + } + catch (Exception ex) + { + //ICSharpCode.Core.LoggingService.Error("停止Socket侦听失败:" + ex.Message); + } + finally + { + //this.listener = null; + } + } + /// + /// 发送消息至所有连接至本服务器的客户端计算机 + /// + /// 消息内容 + public void NetSendMsg(string msg) + { + foreach (string uid in this.listener.OnlineUID) + { + this.listener.Send(uid, msg); + } + } + /// + /// 发送消息至指定计算机 + /// + /// 计算机IP地址 + /// 消息内容 + public void NetSendMsg(string uid, string msg) + { + this.listener.Send(uid, msg); + } + + /// + /// 接收到信息时触发的事件 + /// + public event SocketListener.ReceiveMsgHandler ReceiveMsgHandler; + /// + /// 处理接收客户端连接完成事件 + /// + public event EventHandler ProcessAcceptComplete; + } +} diff --git a/HHWMS.Web/appsettings.json b/HHWMS.Web/appsettings.json index 1bb396b..ec885f7 100644 --- a/HHWMS.Web/appsettings.json +++ b/HHWMS.Web/appsettings.json @@ -24,7 +24,8 @@ "Connections": [ { "Key": "default", - "Value": "Server=(localdb)\\mssqllocaldb;Database=HHWMS;Trusted_Connection=True;MultipleActiveResultSets=true" + "Value": "Server=localhost;Port=3306;Database=8357wms;Uid=root;Password=abc123*;Character Set=utf8mb4;", + "DBType": "mysql" } //{ // "Key": "default", diff --git a/src/WalkingTec.Mvvm.Core/Models/ActionLog.cs b/src/WalkingTec.Mvvm.Core/Models/ActionLog.cs index 3e7c87b..5108107 100644 --- a/src/WalkingTec.Mvvm.Core/Models/ActionLog.cs +++ b/src/WalkingTec.Mvvm.Core/Models/ActionLog.cs @@ -58,6 +58,11 @@ namespace WalkingTec.Mvvm.Core [StringLength(50, ErrorMessage = "Validate.{0}stringmax{1}")] public string TenantCode { get; set; } + [Display(Name = "_Admin.Request")] + public string Request { get; set; } + + [Display(Name = "_Admin.Response")] + public string Result { get; set; } public object Clone() { return this.MemberwiseClone(); @@ -74,6 +79,8 @@ namespace WalkingTec.Mvvm.Core |-Url:{this.ActionUrl ?? ""} |-{Core.CoreProgram._localizer?["_Admin.Duration"]}:{this.Duration.ToString("F2")+" s"} |-{Core.CoreProgram._localizer?["_Admin.Remark"]}:{this.Remark} +|-{Core.CoreProgram._localizer?["_Admin.Request"]}:{this.Request} +|-{Core.CoreProgram._localizer?["_Admin.Result"]}:{this.Result} "; } } diff --git a/src/WalkingTec.Mvvm.Core/WTMContext.cs b/src/WalkingTec.Mvvm.Core/WTMContext.cs index 96d1cee..6f0bd0e 100644 --- a/src/WalkingTec.Mvvm.Core/WTMContext.cs +++ b/src/WalkingTec.Mvvm.Core/WTMContext.cs @@ -4,6 +4,7 @@ using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Linq.Expressions; using System.Net.Http; +using System.Net.Http.Json; using System.Reflection; using System.Runtime.CompilerServices; using System.Text.Json; @@ -824,7 +825,7 @@ params string[] groupcode) return isPublic; } - public void DoLog(string msg, ActionLogTypesEnum logtype = ActionLogTypesEnum.Normal, string moduleName = "", string actionName = "", string ip = "", string url = "", double duration = 0) + public void DoLog(string msg, ActionLogTypesEnum logtype = ActionLogTypesEnum.Normal, string moduleName = "", string actionName = "", string ip = "", string url = "", double duration = 0,string request = "", string result = "") { var log = this.Log?.GetActionLog(); if (log == null) @@ -838,6 +839,8 @@ params string[] groupcode) log.Duration = duration; log.ModuleName = moduleName; log.ActionName = actionName; + log.Request = request; + log.Result = result; log.IP = ip; if (string.IsNullOrEmpty(url) && this.HttpContext?.Request != null) { @@ -1167,6 +1170,7 @@ params string[] groupcode) public async Task> CallAPI(string domainName, string url, HttpMethodEnum method, HttpContent content, int? timeout = null, string proxy = null, Dictionary headers = null) where T : class { ApiResult rv = new ApiResult(); + var request = content.ReadAsStringAsync().Result; try { var factory = this.ServiceProvider.GetRequiredService(); @@ -1183,6 +1187,7 @@ params string[] groupcode) else { client = factory.CreateClient(domainName); + client.BaseAddress = new Uri(ConfigInfo.Domains[domainName.ToLower()].Address); } if (headers != null) { @@ -1266,12 +1271,13 @@ params string[] groupcode) } rv.ErrorMsg = responseTxt; } - + this.DoLog("send",ActionLogTypesEnum.Normal, domainName,url,url:url,request:request,result: JsonSerializer.Serialize(rv.Data)); return rv; } catch (Exception ex) { rv.ErrorMsg = ex.ToString(); + this.DoLog("send", ActionLogTypesEnum.Exception, domainName,url, request: request, result: ex.Message); return rv; } } diff --git a/src/WalkingTec.Mvvm.Mvc/CodeGenVM.cs b/src/WalkingTec.Mvvm.Mvc/CodeGenVM.cs index a1a2ab2..a745386 100644 --- a/src/WalkingTec.Mvvm.Mvc/CodeGenVM.cs +++ b/src/WalkingTec.Mvvm.Mvc/CodeGenVM.cs @@ -134,7 +134,7 @@ namespace WalkingTec.Mvvm.Mvc { get { - if (_sharedir == null) + /*if (_sharedir == null) { var up = Directory.GetParent(MainDir); var sharedir = up.GetDirectories().Where(x => x.Name.ToLower().EndsWith(".shared")).FirstOrDefault(); @@ -148,7 +148,7 @@ namespace WalkingTec.Mvvm.Mvc } _sharedir = sharedir.FullName; - } + }*/ return _sharedir; } } diff --git a/src/WalkingTec.Mvvm.Mvc/Filters/FrameworkFilter.cs b/src/WalkingTec.Mvvm.Mvc/Filters/FrameworkFilter.cs index 280a1f6..1639cfb 100644 --- a/src/WalkingTec.Mvvm.Mvc/Filters/FrameworkFilter.cs +++ b/src/WalkingTec.Mvvm.Mvc/Filters/FrameworkFilter.cs @@ -19,13 +19,18 @@ using WalkingTec.Mvvm.Core.Json; using Microsoft.Extensions.DependencyInjection; using Microsoft.AspNetCore.Mvc.ViewEngines; using WalkingTec.Mvvm.Core.Extensions; +using Microsoft.EntityFrameworkCore.Metadata.Internal; +using System.Dynamic; +using NPOI.SS.Formula.Functions; namespace WalkingTec.Mvvm.Mvc.Filters { public class FrameworkFilter : ActionFilterAttribute { + private string requestMsg = ""; public override void OnActionExecuting(ActionExecutingContext context) { + requestMsg = Newtonsoft.Json.JsonConvert.SerializeObject( context.ActionArguments); var ctrl = context.Controller as IBaseController; if (ctrl == null) { @@ -385,6 +390,12 @@ namespace WalkingTec.Mvvm.Mvc.Filters log.ActionUrl = context.HttpContext.Request.Path; log.IP = context.HttpContext.GetRemoteIpAddress(); log.Remark = context.Exception?.ToString() ?? string.Empty; + log.Request = requestMsg; + if (log.ModuleName.StartsWith("HHWMS")) + { + dynamic reMsg = context.Result as dynamic; + log.Result = Newtonsoft.Json.JsonConvert.SerializeObject(reMsg?.Value); + } if (string.IsNullOrEmpty(log.Remark) == false && log.Remark.Length > 2000) { log.Remark = log.Remark.Substring(0, 2000); diff --git a/src/WalkingTec.Mvvm.TagHelpers.LayUI/DataTableTagHelper.cs b/src/WalkingTec.Mvvm.TagHelpers.LayUI/DataTableTagHelper.cs index 4ebcc1a..056de87 100644 --- a/src/WalkingTec.Mvvm.TagHelpers.LayUI/DataTableTagHelper.cs +++ b/src/WalkingTec.Mvvm.TagHelpers.LayUI/DataTableTagHelper.cs @@ -654,7 +654,7 @@ setTimeout(function(){{ }})