/// <summary> /// 正常下线 /// </summary> /// <param name="session">会话</param> internal override void AppSessionRemoteClose(AppSession session) { session.WorkSocket?.Close( ); System.Threading.Interlocked.Decrement(ref clientCount); LogNet?.WriteDebug(ToString( ), string.Format(StringResources.Language.ClientOfflineInfo, session.IpEndPoint)); }
/// <summary> /// 接收一条完整的数据,使用异步接收完成,包含了指令头信息 /// </summary> /// <param name="socket">已经打开的网络套接字</param> /// <param name="timeOut">超时时间</param> /// <param name="netMsg">消息规则</param> /// <returns>数据的接收结果对象</returns> protected OperateResult <TNetMessage> ReceiveMessage(Socket socket, int timeOut, TNetMessage netMsg) { OperateResult <TNetMessage> result = new OperateResult <TNetMessage>( ); // 超时接收的代码验证 HslTimeOut hslTimeOut = new HslTimeOut( ) { DelayTime = timeOut, WorkSocket = socket, }; if (timeOut > 0) { ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolCheckTimeOut), hslTimeOut); } // 接收指令头 OperateResult <byte[]> headResult = Receive(socket, netMsg.ProtocolHeadBytesLength); if (!headResult.IsSuccess) { hslTimeOut.IsSuccessful = true; result.CopyErrorFromOther(headResult); return(result); } netMsg.HeadBytes = headResult.Content; if (!netMsg.CheckHeadBytesLegal(Token.ToByteArray( ))) { // 令牌校验失败 hslTimeOut.IsSuccessful = true; socket?.Close( ); LogNet?.WriteError(ToString( ), StringResources.TokenCheckFailed); result.Message = StringResources.TokenCheckFailed; return(result); } int contentLength = netMsg.GetContentLengthByHeadBytes( ); if (contentLength == 0) { netMsg.ContentBytes = new byte[0]; } else { OperateResult <byte[]> contentResult = Receive(socket, contentLength); if (!headResult.IsSuccess) { hslTimeOut.IsSuccessful = true; result.CopyErrorFromOther(contentResult); return(result); } netMsg.ContentBytes = contentResult.Content; } hslTimeOut.IsSuccessful = true; result.Content = netMsg; result.IsSuccess = true; return(result); }
private void ModbusHeadReveiveCallback(IAsyncResult ar) { if (ar.AsyncState is ModBusState state) { try { int receiveCount = state.WorkSocket.EndReceive(ar); if (receiveCount == 0) { state.WorkSocket?.Close( ); LogNet?.WriteDebug(ToString( ), $"客户端 [ {state.IpEndPoint} ] 下线"); return; } else { state.HeadByteReceivedLength += receiveCount; } } catch (Exception ex) { // 关闭连接,记录日志 state.WorkSocket?.Close( ); LogNet?.WriteException(ToString(), $"客户端 [ {state.IpEndPoint} ] 异常下线,消息子节接收失败!", ex); return; } try { if (state.HeadByteReceivedLength < state.HeadByte.Length) { // 数据不够,继续接收 state.WorkSocket.BeginReceive(state.HeadByte, state.HeadByteReceivedLength, state.HeadByte.Length - state.HeadByteReceivedLength, SocketFlags.None, new AsyncCallback(ModbusHeadReveiveCallback), state); return; } } catch (Exception ex) { state.WorkSocket?.Close( ); LogNet?.WriteException(ToString( ), $"客户端 [ {state.IpEndPoint} ] 异常下线,再次启动接收失败!", ex); return; } // 准备接收的数据长度 int ContentLength = state.HeadByte[4] * 256 + state.HeadByte[5]; // 第一次过滤,过滤掉不是Modbus Tcp协议的 if (state.HeadByte[2] == 0x00 && state.HeadByte[3] == 0x00 && ContentLength < 300) { try { // 头子节接收完成 state.Content = new byte[ContentLength]; state.ContentReceivedLength = 0; // 开始接收内容 state.WorkSocket.BeginReceive(state.Content, state.ContentReceivedLength, state.Content.Length - state.ContentReceivedLength, SocketFlags.None, new AsyncCallback(ModbusDataReveiveCallback), state); } catch (Exception ex) { state.WorkSocket?.Close( ); LogNet?.WriteException(ToString( ), $"客户端 [ {state.IpEndPoint} ] 异常下线,启动内容接收失败!", ex); return; } } else { // 关闭连接,记录日志 state.WorkSocket?.Close( ); LogNet?.WriteWarn(ToString(), $"客户端 [ {state.IpEndPoint} ] 下线,不是标准的Modbus协议!"); } } }
/// <summary> /// 创建一个新的socket对象并连接到远程的地址 /// </summary> /// <param name="endPoint">连接的目标终结点</param> /// <param name="timeOut">连接的超时时间</param> /// <returns>返回套接字的封装结果对象</returns> /// <example> /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\Core\NetworkBase.cs" region="CreateSocketAndConnectExample" title="创建连接示例" /> /// </example> protected OperateResult <Socket> CreateSocketAndConnect(IPEndPoint endPoint, int timeOut) { if (UseSynchronousNet) { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { HslTimeOut connectTimeout = new HslTimeOut() { WorkSocket = socket, DelayTime = timeOut }; ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolCheckTimeOut), connectTimeout); socket.Connect(endPoint); connectTimeout.IsSuccessful = true; return(OperateResult.CreateSuccessResult(socket)); } catch (Exception ex) { socket?.Close(); LogNet?.WriteException("CreateSocketAndConnect", ex); return(new OperateResult <Socket>(ex.Message)); } } else { OperateResult <Socket> result = new OperateResult <Socket>(); ManualResetEvent connectDone = null; StateObject state = null; try { connectDone = new ManualResetEvent(false); state = new StateObject(); } catch (Exception ex) { return(new OperateResult <Socket>(ex.Message)); } var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 超时验证的信息 HslTimeOut connectTimeout = new HslTimeOut() { WorkSocket = socket, DelayTime = timeOut }; ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolCheckTimeOut), connectTimeout); try { state.WaitDone = connectDone; state.WorkSocket = socket; socket.BeginConnect(endPoint, new AsyncCallback(ConnectCallBack), state); } catch (Exception ex) { // 直接失败 connectTimeout.IsSuccessful = true; // 退出线程池的超时检查 LogNet?.WriteException(ToString(), ex); // 记录错误日志 socket.Close(); // 关闭网络信息 connectDone.Close(); // 释放等待资源 result.Message = StringResources.Language.ConnectedFailed + ex.Message; // 传递错误消息 return(result); } // 等待连接完成 connectDone.WaitOne(); connectDone.Close(); connectTimeout.IsSuccessful = true; if (state.IsError) { // 连接失败 result.Message = StringResources.Language.ConnectedFailed + state.ErrerMsg; socket?.Close(); return(result); } result.Content = socket; result.IsSuccess = true; state.Clear(); state = null; return(result); } }
/// <summary> /// 处理请求接收连接后的方法 /// </summary> /// <param name="obj">Accpt对象</param> protected override void ThreadPoolLogin(object obj) { if (obj is Socket socket) { // 接收一条信息,指定当前请求的数据订阅信息的关键字 OperateResult <int, string> receive = ReceiveStringContentFromSocket(socket); if (!receive.IsSuccess) { return; } // 判断当前的关键字在服务器是否有消息发布 if (!IsPushGroupOnline(receive.Content2)) { SendStringAndCheckReceive(socket, 1, StringResources.Language.KeyIsNotExist); LogNet?.WriteWarn(ToString( ), StringResources.Language.KeyIsNotExist); socket?.Close( ); return; } SendStringAndCheckReceive(socket, 0, ""); // 允许发布订阅信息 AppSession session = new AppSession { KeyGroup = receive.Content2, WorkSocket = socket }; try { session.IpEndPoint = (System.Net.IPEndPoint)socket.RemoteEndPoint; session.IpAddress = session.IpEndPoint.Address.ToString( ); } catch (Exception ex) { LogNet?.WriteException(ToString( ), StringResources.Language.GetClientIpaddressFailed, ex); } try { socket.BeginReceive(session.BytesHead, 0, session.BytesHead.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), session); } catch (Exception ex) { LogNet?.WriteException(ToString( ), StringResources.Language.SocketReceiveException, ex); return; } LogNet?.WriteDebug(ToString( ), string.Format(StringResources.Language.ClientOnlineInfo, session.IpEndPoint)); PushGroupClient push = GetPushGroupClient(receive.Content2); if (push != null) { System.Threading.Interlocked.Increment(ref onlineCount); push.AddPushClient(session); dicSendCacheLock.Enter( ); if (dictSendHistory.ContainsKey(receive.Content2)) { if (isPushCacheAfterConnect) { SendString(session, dictSendHistory[receive.Content2]); } } dicSendCacheLock.Leave( ); } } }
/// <summary> /// 指令头接收方法 /// </summary> /// <param name="ar">异步状态信息</param> protected void HeadBytesReceiveCallback(IAsyncResult ar) { if (ar.AsyncState is AppSession session) { try { int receiveCount = session.WorkSocket.EndReceive(ar); if (receiveCount == 0) { // 断开了连接,需要做个处理,一个是直接关闭,另一个是触发下线 AppSessionRemoteClose(session); return; } else { session.AlreadyReceivedHead += receiveCount; } } catch (ObjectDisposedException) { // 不需要处理,来自服务器主动关闭 return; } catch (SocketException ex) { // 已经断开连接了 SocketReceiveException(session, ex); LogNet?.WriteException(ToString( ), ex); return; } catch (Exception ex) { // 其他乱七八糟的异常重新启用接收数据 ReBeginReceiveHead(session, false); LogNet?.WriteException(ToString( ), StringResources.Language.SocketEndReceiveException, ex); return; } if (session.AlreadyReceivedHead < session.BytesHead.Length) { try { // 仍需要接收 session.WorkSocket.BeginReceive(session.BytesHead, session.AlreadyReceivedHead, session.BytesHead.Length - session.AlreadyReceivedHead, SocketFlags.None, new AsyncCallback(HeadBytesReceiveCallback), session); } catch (Exception ex) { SocketReceiveException(session, ex); LogNet?.WriteException(ToString( ), ex); } } else { // 接收完毕,校验令牌 if (!CheckRemoteToken(session.BytesHead)) { LogNet?.WriteWarn(ToString( ), StringResources.Language.TokenCheckFailed); AppSessionRemoteClose(session); return; } int receive_length = BitConverter.ToInt32(session.BytesHead, session.BytesHead.Length - 4); session.BytesContent = new byte[receive_length]; if (receive_length > 0) { try { int receiveSize = session.BytesContent.Length - session.AlreadyReceivedContent; session.WorkSocket.BeginReceive(session.BytesContent, session.AlreadyReceivedContent, receiveSize, SocketFlags.None, new AsyncCallback(ContentReceiveCallback), session); } catch (Exception ex) { SocketReceiveException(session, ex); LogNet?.WriteException(ToString( ), ex); } } else { // 处理数据并重新启动接收 ReBeginReceiveHead(session, true); } } } }
/***************************************************************************** * * 说明: * 下面的三个模块代码指示了如何接收数据,如何发送数据,如何连接网络 * ********************************************************************************/ #region Reveive Content /// <summary> /// 接收固定长度的字节数组 /// </summary> /// <remarks> /// Receive Special Length Bytes /// </remarks> /// <param name="socket">网络通讯的套接字</param> /// <param name="length">准备接收的数据长度</param> /// <returns>包含了字节数据的结果类</returns> protected OperateResult <byte[]> Receive(Socket socket, int length) { if (length == 0) { return(OperateResult.CreateSuccessResult(new byte[0])); } if (!Authorization.nzugaydgwadawdibbas()) { return(new OperateResult <byte[]>(StringResources.Language.AuthorizationFailed)); } if (UseSynchronousNet) { try { byte[] data = NetSupport.ReadBytesFromSocket(socket, length); return(OperateResult.CreateSuccessResult(data)); } catch (Exception ex) { socket?.Close(); LogNet?.WriteException(ToString(), "Receive", ex); return(new OperateResult <byte[]>(ex.Message)); } } OperateResult <byte[]> result = new OperateResult <byte[]>(); ManualResetEvent receiveDone = null; StateObject state = null; try { receiveDone = new ManualResetEvent(false); state = new StateObject(length); } catch (Exception ex) { return(new OperateResult <byte[]>(ex.Message)); } try { state.WaitDone = receiveDone; state.WorkSocket = socket; // Begin receiving the data from the remote device. socket.BeginReceive(state.Buffer, state.AlreadyDealLength, state.DataLength - state.AlreadyDealLength, SocketFlags.None, new AsyncCallback(ReceiveCallback), state); } catch (Exception ex) { // 发生了错误,直接返回 LogNet?.WriteException(ToString(), ex); result.Message = ex.Message; receiveDone.Close(); socket?.Close(); return(result); } // 等待接收完成,或是发生异常 receiveDone.WaitOne(); receiveDone.Close(); // 接收数据失败 if (state.IsError) { socket?.Close(); result.Message = state.ErrerMsg; return(result); } // 远程关闭了连接 if (state.IsClose) { // result.IsSuccess = true; result.Message = StringResources.Language.RemoteClosedConnection; socket?.Close(); return(result); } // 正常接收到数据 result.Content = state.Buffer; result.IsSuccess = true; state.Clear(); state = null; return(result); }
/// <summary> /// 基础下载信息 /// </summary> /// <param name="factory">一级分类</param> /// <param name="group">二级分类</param> /// <param name="id">三级分类</param> /// <param name="fileName">服务器的文件名称</param> /// <param name="processReport">下载的进度报告</param> /// <param name="source">数据源信息,决定最终存储到哪里去</param> /// <returns>是否成功的结果对象</returns> protected OperateResult DownloadFileBase( string factory, string group, string id, string fileName, Action <long, long> processReport, object source ) { // connect server OperateResult <Socket> socketResult = CreateSocketAndConnect(ServerIpEndPoint, ConnectTimeOut); if (!socketResult.IsSuccess) { return(socketResult); } // 发送操作指令 OperateResult sendString = SendStringAndCheckReceive(socketResult.Content, HslProtocol.ProtocolFileDownload, fileName); if (!sendString.IsSuccess) { return(sendString); } // 发送三级分类 OperateResult sendClass = SendFactoryGroupId(socketResult.Content, factory, group, id); if (!sendClass.IsSuccess) { return(sendClass); } // 根据数据源分析 if (source is string fileSaveName) { OperateResult result = ReceiveFileFromSocket(socketResult.Content, fileSaveName, processReport); if (!result.IsSuccess) { return(result); } } else if (source is Stream stream) { OperateResult result = ReceiveFileFromSocket(socketResult.Content, stream, processReport); if (!result.IsSuccess) { return(result); } } else { socketResult.Content?.Close( ); LogNet?.WriteError(ToString(), "Not supported data type!"); return(new OperateResult( ) { Message = "不支持的数据类型" }); } socketResult.Content?.Close( ); return(OperateResult.CreateSuccessResult( )); }
/// <summary> /// 上传文件给服务器 /// </summary> /// <param name="source">数据源,可以是文件名,也可以是数据流</param> /// <param name="serverName">在服务器保存的文件名,不包含驱动器路径</param> /// <param name="factory">一级分类</param> /// <param name="group">二级分类</param> /// <param name="id">三级分类</param> /// <param name="fileTag">文件的描述</param> /// <param name="fileUpload">文件的上传人</param> /// <param name="processReport">汇报进度</param> /// <returns>是否成功的结果对象</returns> protected OperateResult UploadFileBase( object source, string serverName, string factory, string group, string id, string fileTag, string fileUpload, Action <long, long> processReport) { // HslReadWriteLock readWriteLock = new HslReadWriteLock( ); // 创建套接字并连接服务器 OperateResult <Socket> socketResult = CreateSocketAndConnect(ServerIpEndPoint, ConnectTimeOut); if (!socketResult.IsSuccess) { return(socketResult); } // 上传操作暗号的文件名 OperateResult sendString = SendStringAndCheckReceive(socketResult.Content, HslProtocol.ProtocolFileUpload, serverName); if (!sendString.IsSuccess) { return(sendString); } // 发送三级分类 OperateResult sendClass = SendFactoryGroupId(socketResult.Content, factory, group, id); if (!sendClass.IsSuccess) { return(sendClass); } // 判断数据源格式 if (source is string fileName) { OperateResult result = SendFileAndCheckReceive(socketResult.Content, fileName, serverName, fileTag, fileUpload, processReport); if (!result.IsSuccess) { return(result); } } else if (source is Stream stream) { OperateResult result = SendFileAndCheckReceive(socketResult.Content, stream, serverName, fileTag, fileUpload, processReport); if (!result.IsSuccess) { return(result); } } else { socketResult.Content?.Close( ); LogNet?.WriteError(ToString( ), "数据源格式不正确!"); return(new OperateResult( ) { Message = "数据源格式不正确!", }); } // 确认服务器文件保存状态 OperateResult <int, string> resultCheck = ReceiveStringContentFromSocket(socketResult.Content); if (!resultCheck.IsSuccess) { return(resultCheck); } if (resultCheck.Content1 == 1) { return(OperateResult.CreateSuccessResult( )); } else { return(new OperateResult( ) { Message = "服务器确认文件失败,请重新上传!", }); } }
/// <summary> /// 处理数据 /// </summary> /// <param name="obj">异步对象</param> protected override void ThreadPoolLogin(object obj) { if (obj is Socket socket) { OperateResult result = new OperateResult( ); // 获取ip地址 string IpAddress = ((IPEndPoint)(socket.RemoteEndPoint)).Address.ToString( ); // 接收操作信息 if (!ReceiveInformationHead( socket, out int customer, out string fileName, out string Factory, out string Group, out string Identify).IsSuccess) { return; } string relativeName = ReturnRelativeFileName(Factory, Group, Identify, fileName); if (customer == HslProtocol.ProtocolFileDownload) { // 先获取文件的真实名称 string guidName = TransformFactFileName(Factory, Group, Identify, fileName); // 获取文件操作锁 FileMarkId fileMarkId = GetFileMarksFromDictionaryWithFileName(guidName); fileMarkId.EnterReadOperator( ); // 发送文件数据 OperateResult send = SendFileAndCheckReceive(socket, ReturnAbsoluteFileName(Factory, Group, Identify, guidName), fileName, "", "", null); if (!send.IsSuccess) { fileMarkId.LeaveReadOperator( ); LogNet?.WriteError(ToString( ), $"{StringResources.FileDownloadFailed} : {send.Message} :{relativeName} ip:{IpAddress}"); return; } else { LogNet?.WriteInfo(ToString( ), StringResources.FileDownloadSuccess + ":" + relativeName); } fileMarkId.LeaveReadOperator( ); // 关闭连接 socket?.Close( ); } else if (customer == HslProtocol.ProtocolFileUpload) { string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName); // 上传文件 CheckFolderAndCreate( ); FileInfo info = new FileInfo(fullFileName); try { if (!Directory.Exists(info.DirectoryName)) { Directory.CreateDirectory(info.DirectoryName); } } catch (Exception ex) { LogNet?.WriteException(ToString( ), StringResources.FilePathCreateFailed + fullFileName, ex); socket?.Close( ); return; } // 接收文件并回发消息 if (ReceiveFileFromSocketAndUpdateGroup( socket, // 网络套接字 fullFileName).IsSuccess) { socket?.Close( ); LogNet?.WriteInfo(ToString( ), StringResources.FileUploadSuccess + ":" + relativeName); } else { LogNet?.WriteInfo(ToString( ), StringResources.FileUploadFailed + ":" + relativeName); } } else if (customer == HslProtocol.ProtocolFileDelete) { string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName); FileInfo info = new FileInfo(fullFileName); GroupFileContainer fileManagment = GetGroupFromFilePath(info.DirectoryName); // 新增删除的任务 DeleteExsistingFile(info.DirectoryName, fileManagment.DeleteFile(info.Name)); // 回发消息 if (SendStringAndCheckReceive( socket, // 网络套接字 1, // 没啥含义 "success" // 没啥含意 ).IsSuccess) { socket?.Close( ); } LogNet?.WriteInfo(ToString( ), StringResources.FileDeleteSuccess + ":" + relativeName); } else if (customer == HslProtocol.ProtocolFileDirectoryFiles) { GroupFileContainer fileManagment = GetGroupFromFilePath(ReturnAbsoluteFilePath(Factory, Group, Identify)); if (SendStringAndCheckReceive( socket, HslProtocol.ProtocolFileDirectoryFiles, fileManagment.JsonArrayContent).IsSuccess) { socket?.Close( ); } } else if (customer == HslProtocol.ProtocolFileDirectories) { List <string> folders = new List <string>( ); foreach (var m in GetDirectories(Factory, Group, Identify)) { DirectoryInfo directory = new DirectoryInfo(m); folders.Add(directory.Name); } Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.FromObject(folders.ToArray( )); if (SendStringAndCheckReceive( socket, HslProtocol.ProtocolFileDirectoryFiles, jArray.ToString( )).IsSuccess) { socket?.Close( ); } } else { // close not supported client socket?.Close( ); } } }
private void ContentReveiveCallBack(IAsyncResult ar) { if (ar.AsyncState is ModBusState state) { try { int count = state.WorkSocket.EndReceive(ar); state.ContentReceivedLength += count; if (state.ContentReceivedLength < state.Content.Length) { // 数据不够,继续接收 state.WorkSocket.BeginReceive(state.Content, state.ContentReceivedLength, state.Content.Length - state.ContentReceivedLength, SocketFlags.None, new AsyncCallback(ContentReveiveCallBack), state); } else { // 内容接收完成,所有的数据接收结束 byte[] data = new byte[state.HeadByte.Length + state.Content.Length]; state.HeadByte.CopyTo(data, 0); state.Content.CopyTo(data, state.HeadByte.Length); state.Clear(); // 重新启动接收 state.WorkSocket.BeginReceive(state.HeadByte, state.HeadByteReceivedLength, state.HeadByte.Length, SocketFlags.None, new AsyncCallback(HeadReveiveCallBack), state); if (data[7] == 0x01 || data[7] == 0x02 || data[7] == 0x03) { if (data.Length != 0x0C) { // 指令长度验证错误,关闭网络连接 state.WorkSocket?.Close(); state = null; if (IsStarted) { LogNet?.WriteWarn(LogHeaderText, "Command length check failed!"); } return; } } // 需要回发消息 byte[] copy = null; switch (data[7]) { case 0x01: { // 线圈读取 int address = data[8] * 256 + data[9]; int length = data[10] * 256 + data[11]; if (length > 2048) { length = 2048; // 线圈读取应该小于2048个 } bool[] read = ReadCoil((ushort)address, (ushort)length); byte[] buffer = BasicFramework.SoftBasic.BoolArrayToByte(read); copy = new byte[9 + buffer.Length]; Array.Copy(data, 0, copy, 0, 8); copy[4] = (byte)((copy.Length - 6) / 256); copy[5] = (byte)((copy.Length - 6) % 256); copy[8] = (byte)buffer.Length; Array.Copy(buffer, 0, copy, 9, buffer.Length); break; } case 0x02: { // 离散值读取,本服务器无效 copy = new byte[9]; Array.Copy(data, 0, copy, 0, 8); copy[4] = 0x00; copy[5] = 0x03; break; } case 0x03: { // 寄存器读取 int address = data[8] * 256 + data[9]; int length = data[10] * 256 + data[11]; if (length > 127) { length = 127; // 寄存器最大读取范围为127个 } byte[] buffer = ReadRegister((ushort)address, (ushort)length); copy = new byte[9 + buffer.Length]; Array.Copy(data, 0, copy, 0, 8); copy[4] = (byte)((copy.Length - 6) / 256); copy[5] = (byte)((copy.Length - 6) % 256); copy[8] = (byte)buffer.Length; Array.Copy(buffer, 0, copy, 9, buffer.Length); break; } case 0x05: { // 写单个线圈 int address = data[8] * 256 + data[9]; if (data[10] == 0xFF && data[11] == 0x00) { WriteCoil((ushort)address, true); } else if (data[10] == 0x00 && data[11] == 0x00) { WriteCoil((ushort)address, false); } copy = new byte[12]; Array.Copy(data, 0, copy, 0, 12); copy[4] = 0x00; copy[5] = 0x06; break; } case 0x06: { // 写单个寄存器 ushort address = (ushort)(data[8] * 256 + data[9]); short ValueOld = ReadShortRegister(address); // 写入到寄存器 WriteRegister(address, data[10], data[11]); short ValueNew = ReadShortRegister(address); // 触发写入请求 OnRegisterBeforWrite(address, ValueOld, ValueNew); copy = new byte[12]; Array.Copy(data, 0, copy, 0, 12); copy[4] = 0x00; copy[5] = 0x06; break; } case 0x0F: { // 写多个线圈 int address = data[8] * 256 + data[9]; int length = data[10] * 256 + data[11]; byte[] buffer = new byte[data.Length - 13]; Array.Copy(data, 13, buffer, 0, buffer.Length); bool[] value = BasicFramework.SoftBasic.ByteToBoolArray(buffer, length); WriteCoil((ushort)address, value); copy = new byte[12]; Array.Copy(data, 0, copy, 0, 12); copy[4] = 0x00; copy[5] = 0x06; break; } case 0x10: { // 写多个寄存器 int address = data[8] * 256 + data[9]; int length = data[10] * 256 + data[11]; byte[] buffer = new byte[data.Length - 13]; for (int i = 0; i < length; i++) { if ((2 * i + 14) < data.Length) { short ValueOld = ReadShortRegister((ushort)(address + i)); WriteRegister((ushort)(address + i), data[2 * i + 13], data[2 * i + 14]); short ValueNew = ReadShortRegister((ushort)(address + i)); // 触发写入请求 OnRegisterBeforWrite((ushort)(address + i), ValueOld, ValueNew); } } copy = new byte[12]; Array.Copy(data, 0, copy, 0, 12); copy[4] = 0x00; copy[5] = 0x06; break; } default: { if (IsStarted) { LogNet?.WriteWarn(LogHeaderText, "Unknown Function Code:" + data[7]); } copy = new byte[12]; Array.Copy(data, 0, copy, 0, 12); copy[4] = 0x00; copy[5] = 0x06; break; } } // 通知处理消息 if (IsStarted) { OnDataReceived?.Invoke(data); } // 回发数据,先获取发送锁 state.hybirdLock.Enter(); state.WorkSocket.BeginSend(copy, 0, size: copy.Length, socketFlags: SocketFlags.None, callback: new AsyncCallback(DataSendCallBack), state: state); } } catch (Exception ex) { // 关闭连接,记录日志 state.WorkSocket?.Close(); state = null; if (IsStarted) { LogNet?.WriteException(LogHeaderText, "内容数据接收失败!", ex); } } } }
public string SaveModelListSqlToDBADF(User.UserModel user, List <TBase_Model> modelList) { BaseMessage_Model <List <TBase_Model> > model = new BaseMessage_Model <List <TBase_Model> >(); try { bool bSucc = false; string strError = ""; if (user == null) { model.HeaderStatus = "E"; model.Message = "传入用户信息为空!"; JsonConvert.SerializeObject(model); } if (CheckModelBeforeSave(modelList, ref strError) == false) { model.HeaderStatus = "E"; model.Message = strError; JsonConvert.SerializeObject(model); } T_Interface_Func tfunc = new T_Interface_Func(); string ERPJson = GetModelListByJsonToERP(user, modelList);//JSONUtil.JSONHelper.ObjectToJson<List<TBase_Model>>(modelList); LogNet.LogInfo("ERPJsonBefore:" + ERPJson); string interfaceJson = tfunc.PostModelListToInterface(ERPJson); model = JSONUtil.JSONHelper.JsonToObject <BaseMessage_Model <List <TBase_Model> > >(interfaceJson); LogNet.LogInfo("ERPJsonAfter:" + JSONUtil.JSONHelper.ObjectToJson <BaseMessage_Model <List <TBase_Model> > >(model)); //过账失败直接返回 if (model.HeaderStatus == "E" && !string.IsNullOrEmpty(model.Message)) { return(interfaceJson); } else if (model.HeaderStatus == "S" && !string.IsNullOrEmpty(model.MaterialDoc)) //过账成功,并且生成了凭证要记录数据库 { modelList.ForEach(t => t.MaterialDoc = model.MaterialDoc); } //LogNet.LogInfo("ERPJson:" + JSONUtil.JSONHelper.ObjectToJson<List<TBase_Model>>(modelList)); bSucc = db.SaveModelListBySqlToDB(user, ref modelList, ref strError); if (bSucc == false) { model.HeaderStatus = "E"; model.Message = strError; } else { model.HeaderStatus = "S"; model.TaskNo = modelList[0].TaskNo; model.Message = GetSuccessMessage(model.MaterialDoc, modelList[0].TaskNo); } return(JsonConvert.SerializeObject(model)); } catch (Exception ex) { model.HeaderStatus = "E"; model.Message = "保存" + GetModelChineseName() + "失败!" + ex.Message + ex.TargetSite; return(JsonConvert.SerializeObject(model)); } }
/***************************************************************************** * * 说明: * 下面的三个模块代码指示了如何接收数据,如何发送数据,如何连接网络 * ********************************************************************************/ #region Reveive Content /// <summary> /// 接收固定长度的字节数组 /// </summary> /// <remarks> /// Receive Special Length Bytes /// </remarks> /// <param name="socket">网络通讯的套接字</param> /// <param name="length">准备接收的数据长度</param> /// <returns>包含了字节数据的结果类</returns> protected OperateResult <byte[]> Receive(Socket socket, int length) { if (length == 0) { return(OperateResult.CreateSuccessResult(new byte[0])); } var result = new OperateResult <byte[]>( ); var receiveDone = new ManualResetEvent(false); var state = new StateObject(length); try { state.WaitDone = receiveDone; state.WorkSocket = socket; // Begin receiving the data from the remote device. socket.BeginReceive(state.Buffer, state.AlreadyDealLength, state.DataLength - state.AlreadyDealLength, SocketFlags.None, new AsyncCallback(ReceiveCallback), state); } catch (Exception ex) { // 发生了错误,直接返回 LogNet?.WriteException(ToString( ), ex); result.Message = ex.Message; receiveDone.Close( ); socket?.Close( ); return(result); } // 等待接收完成,或是发生异常 receiveDone.WaitOne( ); receiveDone.Close( ); // 接收数据失败 if (state.IsError) { socket?.Close( ); result.Message = state.ErrerMsg; return(result); } // 远程关闭了连接 if (state.IsClose) { // result.IsSuccess = true; result.Message = "远程关闭了连接"; socket?.Close( ); return(result); } // 正常接收到数据 result.Content = state.Buffer; result.IsSuccess = true; state.Clear( ); state = null; return(result); }
private void AsyncCallback(IAsyncResult ar) { if (ar.AsyncState is AppSession session) { try { int received = session.WorkSocket.EndReceiveFrom(ar, ref session.UdpEndPoint); // 释放连接关联 session.WorkSocket = null; // 马上开始重新接收,提供性能保障 RefreshReceive( ); // 处理数据 if (received >= HslProtocol.HeadByteLength) { // 检测令牌 if (CheckRemoteToken(session.BytesContent)) { session.IpEndPoint = (IPEndPoint)session.UdpEndPoint; int contentLength = BitConverter.ToInt32(session.BytesContent, HslProtocol.HeadByteLength - 4); if (contentLength == received - HslProtocol.HeadByteLength) { byte[] head = new byte[HslProtocol.HeadByteLength]; byte[] content = new byte[contentLength]; Array.Copy(session.BytesContent, 0, head, 0, HslProtocol.HeadByteLength); if (contentLength > 0) { Array.Copy(session.BytesContent, 32, content, 0, contentLength); } // 解析内容 content = HslProtocol.CommandAnalysis(head, content); int protocol = BitConverter.ToInt32(head, 0); int customer = BitConverter.ToInt32(head, 4); // 丢给数据中心处理 DataProcessingCenter(session, protocol, customer, content); } else { // 否则记录到日志 LogNet?.WriteWarn(ToString(), $"Should Rece:{(BitConverter.ToInt32( session.BytesContent, 4 ) + 8)} Actual:{received}"); } } else { LogNet?.WriteWarn(ToString( ), StringResources.Language.TokenCheckFailed); } } else { LogNet?.WriteWarn(ToString( ), $"Receive error, Actual:{received}"); } } catch (ObjectDisposedException) { //主程序退出的时候触发 } catch (Exception ex) { LogNet?.WriteException(ToString( ), StringResources.Language.SocketEndReceiveException, ex); //重新接收,此处已经排除掉了对象释放的异常 RefreshReceive( ); } finally { //state = null; } } }
/// <summary> /// 处理异常的方法 /// </summary> /// <param name="session"></param> /// <param name="ex">异常信息</param> internal override void SocketReceiveException(AppSession session, Exception ex) { session.WorkSocket?.Close( ); LogNet?.WriteDebug(ToString( ), $"客户端 [ {session.IpEndPoint} ] 异常下线"); }
/// <summary> /// 登录后的处理方法 /// </summary> /// <param name="obj"></param> protected override void ThreadPoolLogin(object obj) { if (obj is Socket socket) { // 判断连接数是否超出规定 if (All_sockets_connect.Count > ConnectMax) { socket?.Close(); LogNet?.WriteWarn(LogHeaderText, StringResources.NetClientFull); return; } // 接收用户别名并验证令牌 OperateResult result = new OperateResult(); if (!ReceiveStringFromSocket( socket, out int customer, out string login_alias, result, null )) { socket?.Close(); return; } // 登录成功 AsyncStateOne stateone = new AsyncStateOne() { WorkSocket = socket, LoginAlias = login_alias, IpEndPoint = (IPEndPoint)socket.RemoteEndPoint, IpAddress = ((IPEndPoint)socket.RemoteEndPoint).Address.ToString(), }; if (customer == 1) { // 电脑端客户端 stateone.ClientType = "Windows"; } else if (customer == 2) { // Android 客户端 stateone.ClientType = "Android"; } try { stateone.WorkSocket.BeginReceive(stateone.BytesHead, stateone.AlreadyReceivedHead, stateone.BytesHead.Length - stateone.AlreadyReceivedHead, SocketFlags.None, new AsyncCallback(HeadReceiveCallback), stateone); TcpStateUpLine(stateone); Thread.Sleep(500);//留下一些时间进行反应 } catch (Exception ex) { //登录前已经出错 TcpStateClose(stateone); LogNet?.WriteException(LogHeaderText, StringResources.NetClientLoginFailed, ex); } } }
/// <summary> /// 正常下线 /// </summary> /// <param name="session"></param> internal override void AppSessionRemoteClose(AppSession session) { session.WorkSocket?.Close( ); LogNet?.WriteDebug(ToString( ), $"客户端 [ {session.IpEndPoint} ] 下线"); }
private void ThreadLogin( ) { lock (lock_connecting) { if (Is_Client_Connecting) { return; } Is_Client_Connecting = true; } if (Connect_Failed_Count == 0) { MessageAlerts?.Invoke("正在连接服务器..."); } else { int count = 10; while (count > 0) { if (IsQuie) { return; } MessageAlerts?.Invoke("连接断开,等待" + count-- + "秒后重新连接"); Thread.Sleep(1000); } MessageAlerts?.Invoke("正在尝试第" + Connect_Failed_Count + "次连接服务器..."); } stateone.HeartTime = DateTime.Now; LogNet?.WriteDebug(ToString( ), "Begin Connect Server, Times: " + Connect_Failed_Count); OperateResult result = new OperateResult( ); OperateResult <Socket> connectResult = CreateSocketAndConnect(EndPointServer, 10000); if (!connectResult.IsSuccess) { Connect_Failed_Count++; Is_Client_Connecting = false; LoginFailed?.Invoke(Connect_Failed_Count); LogNet?.WriteDebug(ToString( ), "Connected Failed, Times: " + Connect_Failed_Count); // 连接失败,重新连接服务器 ReconnectServer( ); return; } // 连接成功,发送数据信息 OperateResult sendResult = SendStringAndCheckReceive(connectResult.Content, 1, ClientAlias); if (!sendResult.IsSuccess) { Connect_Failed_Count++; Is_Client_Connecting = false; LogNet?.WriteDebug(ToString( ), "Login Server Failed, Times: " + Connect_Failed_Count); LoginFailed?.Invoke(Connect_Failed_Count); // 连接失败,重新连接服务器 ReconnectServer( ); return; } // 登录成功 Connect_Failed_Count = 0; stateone.IpEndPoint = (IPEndPoint)connectResult.Content.RemoteEndPoint; stateone.LoginAlias = ClientAlias; stateone.WorkSocket = connectResult.Content; stateone.WorkSocket.BeginReceive(stateone.BytesHead, stateone.AlreadyReceivedHead, stateone.BytesHead.Length - stateone.AlreadyReceivedHead, SocketFlags.None, new AsyncCallback(HeadBytesReceiveCallback), stateone); // 发送一条验证消息 // SendBytes(stateone, CommunicationCode.CommandBytes(CommunicationCode.Hsl_Protocol_Check_Secends)); byte[] bytesTemp = new byte[16]; BitConverter.GetBytes(DateTime.Now.Ticks).CopyTo(bytesTemp, 0); SendBytes(stateone, HslProtocol.CommandBytes(HslProtocol.ProtocolCheckSecends, 0, Token, bytesTemp)); stateone.HeartTime = DateTime.Now; Is_Client_Start = true; LoginSuccess?.Invoke( ); LogNet?.WriteDebug(ToString( ), "Login Server Success, Times: " + Connect_Failed_Count); Is_Client_Connecting = false; Thread.Sleep(1000); }
/// <summary> /// 当接收到了新的请求的时候执行的操作 /// </summary> /// <param name="socket">异步对象</param> /// <param name="endPoint">终结点</param> protected override void ThreadPoolLogin(Socket socket, IPEndPoint endPoint) { // 判断连接数是否超出规定 if (appSessions.Count > ConnectMax) { socket?.Close( ); LogNet?.WriteWarn(ToString( ), StringResources.Language.NetClientFull); return; } // 接收用户别名并验证令牌 OperateResult result = new OperateResult( ); OperateResult <int, string> readResult = ReceiveStringContentFromSocket(socket); if (!readResult.IsSuccess) { return; } // 登录成功 AppSession session = new AppSession( ) { WorkSocket = socket, LoginAlias = readResult.Content2, }; try { session.IpEndPoint = (IPEndPoint)socket.RemoteEndPoint; session.IpAddress = ((IPEndPoint)socket.RemoteEndPoint).Address.ToString( ); } catch (Exception ex) { LogNet?.WriteException(ToString( ), StringResources.Language.GetClientIpaddressFailed, ex); } if (readResult.Content1 == 1) { // 电脑端客户端 session.ClientType = "Windows"; } else if (readResult.Content1 == 2) { // Android 客户端 session.ClientType = "Android"; } try { session.WorkSocket.BeginReceive(session.BytesHead, session.AlreadyReceivedHead, session.BytesHead.Length - session.AlreadyReceivedHead, SocketFlags.None, new AsyncCallback(HeadBytesReceiveCallback), session); TcpStateUpLine(session); Thread.Sleep(100); // 留下一些时间进行反应 } catch (Exception ex) { // 登录前已经出错 TcpStateClose(session); LogNet?.WriteException(ToString( ), StringResources.Language.NetClientLoginFailed, ex); } }
public string GetOutTaskDetailListByHeaderIDADF(string ModelDetailJson) { BaseMessage_Model <List <T_OutStockTaskDetailsInfo> > messageModel = new BaseMessage_Model <List <T_OutStockTaskDetailsInfo> >(); try { string strError = string.Empty; if (string.IsNullOrEmpty(ModelDetailJson)) { messageModel.HeaderStatus = "E"; messageModel.Message = "客户端传来拣货单JSON为空!"; return(JsonConvert.SerializeObject(messageModel)); } LogNet.LogInfo("GetOutTaskDetailListByHeaderIDADF--" + ModelDetailJson); List <T_OutStockTaskInfo> lstModel = JsonConvert.DeserializeObject <List <T_OutStockTaskInfo> >(ModelDetailJson);//JSONHelper.JsonToObject<List<T_OutStockTaskInfo>>(ModelDetailJson); if (lstModel == null || lstModel.Count == 0) { messageModel.HeaderStatus = "E"; messageModel.Message = "拣货单JSON转换拣货单列表为空!"; return(JsonConvert.SerializeObject(messageModel)); } if (CheckERPVoucherNoIsSame(lstModel, ref strError) == false) { messageModel.HeaderStatus = "E"; messageModel.Message = strError; return(JsonConvert.SerializeObject(messageModel)); } T_OutTaskDetails_DB _db = new T_OutTaskDetails_DB(); List <T_OutStockTaskDetailsInfo> modelList = _db.GetOutTaskDetailListByHeaderIDADF(lstModel); if (modelList == null || modelList.Count == 0) { messageModel.HeaderStatus = "E"; messageModel.Message = "获取拣货单表体列表为空!"; return(JsonConvert.SerializeObject(messageModel)); } modelList = modelList.Where(t => t.RemainQty > 0).ToList(); if (modelList == null || modelList.Count == 0) { messageModel.HeaderStatus = "E"; messageModel.Message = "该拣货单已经全部完成拣货!"; return(JsonConvert.SerializeObject(messageModel)); } //如果拣货单明细没有仓库,增加当前登陆仓库 if (string.IsNullOrEmpty(modelList[0].FromErpWarehouse)) { modelList.ForEach(t => t.FromErpWarehouse = lstModel[0].WareHouseNo); } //拣货分配规则 Context <T_OutStockTaskDetailsInfo> context = new Context <T_OutStockTaskDetailsInfo>(RuleAll_Config.OutStockPickItem); if (context.GetOutStockTaskDetailPickList(ref modelList, ref strError) == false) { messageModel.HeaderStatus = "E"; messageModel.Message = strError; return(JsonConvert.SerializeObject(messageModel)); } modelList.ForEach(t => t.ScanQty = 0); LogNet.LogInfo("GetT_OutTaskDetailListByHeaderIDADF--" + JsonConvert.SerializeObject(modelList)); messageModel.HeaderStatus = "S"; messageModel.ModelJson = modelList; return(JsonConvert.SerializeObject(messageModel)); } catch (Exception ex) { messageModel.HeaderStatus = "E"; messageModel.Message = ex.Message; return(JsonConvert.SerializeObject(messageModel)); } }
/// <summary> /// 发送消息给套接字,直到完成的时候返回 /// </summary> /// <param name="socket">网络套接字</param> /// <param name="data">字节数据</param> /// <returns>发送是否成功的结果</returns> protected OperateResult Send(Socket socket, byte[] data) { if (data == null) { return(OperateResult.CreateSuccessResult()); } if (!Authorization.nzugaydgwadawdibbas()) { return(new OperateResult <byte[]>(StringResources.Language.AuthorizationFailed)); } if (UseSynchronousNet) { try { socket.Send(data); return(OperateResult.CreateSuccessResult()); } catch (Exception ex) { socket?.Close(); LogNet?.WriteException("Send", ex); return(new OperateResult <byte[]>(ex.Message)); } } OperateResult result = new OperateResult(); ManualResetEvent sendDone = null; StateObject state = null; try { sendDone = new ManualResetEvent(false); state = new StateObject(data.Length); } catch (Exception ex) { return(new OperateResult(ex.Message)); } try { state.WaitDone = sendDone; state.WorkSocket = socket; state.Buffer = data; socket.BeginSend(state.Buffer, state.AlreadyDealLength, state.DataLength - state.AlreadyDealLength, SocketFlags.None, new AsyncCallback(SendCallBack), state); } catch (Exception ex) { // 发生了错误,直接返回 LogNet?.WriteException(ToString(), ex); result.Message = ex.Message; socket?.Close(); sendDone.Close(); return(result); } // 等待发送完成 sendDone.WaitOne(); sendDone.Close(); if (state.IsError) { socket.Close(); result.Message = state.ErrerMsg; return(result); } state.Clear(); state = null; result.IsSuccess = true; result.Message = StringResources.Language.SuccessText; return(result); }
public string GetOutTaskDetailListByHeaderIDADF(List <T_OutStockTaskInfo> modelList) { BaseMessage_Model <List <T_OutStockTaskDetailsInfo> > messageModel = new BaseMessage_Model <List <T_OutStockTaskDetailsInfo> >(); try { string strError = string.Empty; if (modelList == null || modelList.Count == 0) { messageModel.HeaderStatus = "E"; messageModel.Message = Language_CHS.DataIsEmpty; return(JsonConvert.SerializeObject(messageModel)); } //if (CheckERPVoucherNoIsSame(lstModel, ref strError) == false) //{ // messageModel.HeaderStatus = "E"; // messageModel.Message = strError; // return BILBasic.JSONUtil.JSONHelper.ObjectToJson<BaseMessage_Model<List<T_OutStockTaskDetailsInfo>>>(messageModel); //} T_OutTaskDetails_DB _db = new T_OutTaskDetails_DB(); List <T_OutStockTaskDetailsInfo> modelListDetail = _db.GetOutTaskDetailListByHeaderIDADF(modelList); modelListDetail = modelListDetail.Where(t => t.RemainQty > 0).ToList(); if (modelListDetail == null || modelListDetail.Count == 0) { messageModel.HeaderStatus = "E"; messageModel.Message = "获取拣货单表体列表为空!"; return(JsonConvert.SerializeObject(messageModel)); } //拣货分配规则 Context <T_OutStockTaskDetailsInfo> context = new Context <T_OutStockTaskDetailsInfo>(RuleAll_Config.OutStockPickItem); if (context.GetOutStockTaskDetailPickList(ref modelListDetail, ref strError) == false) { messageModel.HeaderStatus = "E"; messageModel.Message = strError; return(JsonConvert.SerializeObject(messageModel)); } //List<T_StockInfo> lstStock = new List<T_StockInfo>(); //List<T_OutStockTaskDetailsInfo> modelListGroup = GroupInstockDetailList(modelListDetail); //if (_db.GetPickRuleAreaNo(modelListGroup, ref lstStock, ref strError) == false) //{ // messageModel.HeaderStatus = "E"; // messageModel.Message = strError; // return JsonConvert.SerializeObject(messageModel); //} //if (lstStock != null && lstStock.Count > 0) //{ // lstStock = lstStock.Where(t => t.AreaNo != "NOSALES").ToList(); //} //if (lstStock == null || lstStock.Count == 0) //{ // messageModel.HeaderStatus = "E"; // messageModel.Message = "获取推荐库位库存数量为零!"; // return BILBasic.JSONUtil.JSONHelper.ObjectToJson<BaseMessage_Model<List<T_OutStockTaskDetailsInfo>>>(messageModel); //} //List<T_OutStockTaskDetailsInfo> NewModelList = _db.CreateNewListByPickRuleAreaNo(modelList, lstStock); LogNet.LogInfo("GetT_OutTaskDetailListByHeaderIDADF--" + JsonConvert.SerializeObject(modelListDetail)); messageModel.HeaderStatus = "S"; messageModel.ModelJson = modelListDetail; return(JsonConvert.SerializeObject(messageModel)); } catch (Exception ex) { messageModel.HeaderStatus = "E"; messageModel.Message = ex.Message; return(JsonConvert.SerializeObject(messageModel)); } }
/// <summary> /// 处理数据 /// </summary> /// <param name="obj"></param> protected override void ThreadPoolLogin(object obj) { if (obj is Socket socket) { OperateResult result = new OperateResult( ); // 获取ip地址 string IpAddress = ((IPEndPoint)(socket.RemoteEndPoint)).Address.ToString( ); // 接收操作信息 OperateResult infoResult = ReceiveInformationHead( socket, out int customer, out string fileName, out string Factory, out string Group, out string Identify); if (!infoResult.IsSuccess) { Console.WriteLine(infoResult.ToMessageShowString( )); return; } string relativeName = ReturnRelativeFileName(Factory, Group, Identify, fileName); // 操作分流 if (customer == HslProtocol.ProtocolFileDownload) { string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName); // 发送文件数据 OperateResult sendFile = SendFileAndCheckReceive(socket, fullFileName, fileName, "", ""); if (!sendFile.IsSuccess) { LogNet?.WriteError(ToString( ), $"{StringResources.FileDownloadFailed}:{relativeName} ip:{IpAddress} 原因:{sendFile.Message}"); return; } else { socket?.Close( ); LogNet?.WriteInfo(ToString( ), StringResources.FileDownloadSuccess + ":" + relativeName); } } else if (customer == HslProtocol.ProtocolFileUpload) { string tempFileName = FilesDirectoryPathTemp + "\\" + CreateRandomFileName( ); string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName); // 上传文件 CheckFolderAndCreate( ); // 创建新的文件夹 try { FileInfo info = new FileInfo(fullFileName); if (!Directory.Exists(info.DirectoryName)) { Directory.CreateDirectory(info.DirectoryName); } } catch (Exception ex) { LogNet?.WriteException(ToString( ), "创建文件夹失败:" + fullFileName, ex); socket?.Close( ); return; } OperateResult receiveFile = ReceiveFileFromSocketAndMoveFile( socket, // 网络套接字 tempFileName, // 临时保存文件路径 fullFileName, // 最终保存文件路径 out string FileName, // 文件名称,从客户端上传到服务器时,为上传人 out long FileSize, out string FileTag, out string FileUpload ); if (receiveFile.IsSuccess) { socket?.Close( ); LogNet?.WriteInfo(ToString( ), StringResources.FileUploadSuccess + ":" + relativeName); } else { LogNet?.WriteInfo(ToString( ), StringResources.FileUploadFailed + ":" + relativeName + " 原因:" + receiveFile.Message); } } else if (customer == HslProtocol.ProtocolFileDelete) { string fullFileName = ReturnAbsoluteFileName(Factory, Group, Identify, fileName); bool deleteResult = DeleteFileByName(fullFileName); // 回发消息 if (SendStringAndCheckReceive( socket, // 网络套接字 deleteResult ? 1 : 0, // 是否移动成功 deleteResult ? "成功" : "失败" // 字符串数据 ).IsSuccess) { socket?.Close( ); } if (deleteResult) { LogNet?.WriteInfo(ToString( ), StringResources.FileDeleteSuccess + ":" + relativeName); } } else if (customer == HslProtocol.ProtocolFileDirectoryFiles) { List <GroupFileItem> fileNames = new List <GroupFileItem>( ); foreach (var m in GetDirectoryFiles(Factory, Group, Identify)) { FileInfo fileInfo = new FileInfo(m); fileNames.Add(new GroupFileItem( ) { FileName = fileInfo.Name, FileSize = fileInfo.Length, }); } Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.FromObject(fileNames.ToArray( )); if (SendStringAndCheckReceive( socket, HslProtocol.ProtocolFileDirectoryFiles, jArray.ToString( )).IsSuccess) { socket?.Close( ); } } else if (customer == HslProtocol.ProtocolFileDirectories) { List <string> folders = new List <string>( ); foreach (var m in GetDirectories(Factory, Group, Identify)) { DirectoryInfo directory = new DirectoryInfo(m); folders.Add(directory.Name); } Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.FromObject(folders.ToArray( )); if (SendStringAndCheckReceive( socket, HslProtocol.ProtocolFileDirectoryFiles, jArray.ToString( )).IsSuccess) { socket?.Close( ); } } else { socket?.Close( ); } } }
/// <summary> /// 保存拣货散件箱码 /// </summary> /// <param name="UserJson"></param> /// <param name="ModelJson"></param> /// <returns></returns> public string SaveBoxListADF(string UserJson, string ModelJson) { BaseMessage_Model <List <T_BoxingInfo> > messageModel = new BaseMessage_Model <List <T_BoxingInfo> >(); try { LogNet.LogInfo("SaveBoxListADF--" + JsonConvert.SerializeObject(ModelJson)); string strError = string.Empty; if (string.IsNullOrEmpty(UserJson)) { messageModel.HeaderStatus = "E"; messageModel.Message = "用户端传来用户JSON为空!"; return(BILBasic.JSONUtil.JSONHelper.ObjectToJson <BaseMessage_Model <List <T_BoxingInfo> > >(messageModel)); } if (string.IsNullOrEmpty(ModelJson)) { messageModel.HeaderStatus = "E"; messageModel.Message = "客户端传来拣货单JSON为空!"; return(BILBasic.JSONUtil.JSONHelper.ObjectToJson <BaseMessage_Model <List <T_BoxingInfo> > >(messageModel)); } UserModel user = JSONHelper.JsonToObject <UserModel>(UserJson); if (user == null) { messageModel.HeaderStatus = "E"; messageModel.Message = "用户JSON转换用户列表为空!"; return(BILBasic.JSONUtil.JSONHelper.ObjectToJson <BaseMessage_Model <List <T_BoxingInfo> > >(messageModel)); } List <T_BoxingInfo> modelList = JSONHelper.JsonToObject <List <T_BoxingInfo> >(ModelJson); if (modelList == null || modelList.Count == 0) { messageModel.HeaderStatus = "E"; messageModel.Message = "装箱清单JSON转换列表为空!"; return(BILBasic.JSONUtil.JSONHelper.ObjectToJson <BaseMessage_Model <List <T_BoxingInfo> > >(messageModel)); } var NewModelList = GroupBoxDetailList(modelList); List <T_OutStockTaskDetailsInfo> outTaskDetail = new List <T_OutStockTaskDetailsInfo>(); string strFilter = "erpvoucherno = '" + NewModelList[0].ErpVoucherNo + "'"; bool bSucc = base.GetModelListByFilter(ref outTaskDetail, ref strError, "", strFilter, "*"); if (bSucc == false) { messageModel.HeaderStatus = "E"; messageModel.Message = strError; return(JsonConvert.SerializeObject(messageModel)); } if (outTaskDetail[0].VoucherType == 31)//调拨出 { NewModelList.ForEach(t => t.CustomerNo = outTaskDetail[0].ToErpWarehouse); NewModelList.ForEach(t => t.CustomerName = outTaskDetail[0].ToErpWarehouse); } else { NewModelList.ForEach(t => t.CustomerNo = outTaskDetail[0].SupCusCode); NewModelList.ForEach(t => t.CustomerName = outTaskDetail[0].SupCusName); } string VoucherNo = string.Empty; T_OutStockTask_DB _db = new T_OutStockTask_DB(); if (_db.SaveBoxList(user, NewModelList, ref VoucherNo, ref strError) == false) { messageModel.HeaderStatus = "E"; messageModel.Message = strError; return(BILBasic.JSONUtil.JSONHelper.ObjectToJson <BaseMessage_Model <List <T_BoxingInfo> > >(messageModel)); } else { NewModelList.ForEach(t => t.SerialNo = VoucherNo); messageModel.HeaderStatus = "S"; messageModel.MaterialDoc = VoucherNo; messageModel.ModelJson = NewModelList; return(BILBasic.JSONUtil.JSONHelper.ObjectToJson <BaseMessage_Model <List <T_BoxingInfo> > >(messageModel)); } //T_OutStockTask_DB _db = new T_OutStockTask_DB(); //if (_db.SavePickUserList(UserList, modelList, ref strError) == false) //{ // messageModel.HeaderStatus = "E"; // messageModel.Message = strError; // return BILBasic.JSONUtil.JSONHelper.ObjectToJson<BaseMessage_Model<List<T_OutStockTaskInfo>>>(messageModel); //} //else //{ // messageModel.HeaderStatus = "S"; // messageModel.Message = "拣货任务分配成功!"; // return BILBasic.JSONUtil.JSONHelper.ObjectToJson<BaseMessage_Model<List<T_OutStockTaskInfo>>>(messageModel); //} } catch (Exception ex) { messageModel.HeaderStatus = "E"; messageModel.Message = ex.Message; return(BILBasic.JSONUtil.JSONHelper.ObjectToJson <BaseMessage_Model <List <T_BoxingInfo> > >(messageModel)); } }
private void AsyncCallback(IAsyncResult ar) { if (ar.AsyncState is AsyncStateOne state) { try { int received = state.WorkSocket.EndReceiveFrom(ar, ref state.UdpEndPoint); //释放连接关联 state.WorkSocket = null; //马上开始重新接收,提供性能保障 RefreshReceive(); //处理数据 if (received >= HslCommunicationCode.HeadByteLength) { //检测令牌 if (NetSupport.IsTwoBytesEquel(state.BytesContent, 12, KeyToken.ToByteArray(), 0, 16)) { state.IpEndPoint = (IPEndPoint)state.UdpEndPoint; int contentLength = BitConverter.ToInt32(state.BytesContent, HslCommunicationCode.HeadByteLength - 4); if (contentLength == received - HslCommunicationCode.HeadByteLength) { byte[] head = new byte[HslCommunicationCode.HeadByteLength]; byte[] content = new byte[contentLength]; Array.Copy(state.BytesContent, 0, head, 0, HslCommunicationCode.HeadByteLength); if (contentLength > 0) { Array.Copy(state.BytesContent, 32, content, 0, contentLength); } //解析内容 content = NetSupport.CommandAnalysis(head, content); int protocol = BitConverter.ToInt32(head, 0); int customer = BitConverter.ToInt32(head, 4); //丢给数据中心处理 DataProcessingCenter(state, protocol, customer, content); } else { //否则记录到日志 LogNet?.WriteWarn($"接收到异常数据,应接收长度:{(BitConverter.ToInt32(state.BytesContent, 4) + 8)} 实际接收:{received}"); } } else { LogNet?.WriteWarn(StringResources.TokenCheckFailed); } } else { LogNet?.WriteWarn($"接收到异常数据,长度不符合要求,实际接收:{received}"); } } catch (ObjectDisposedException ex) { //主程序退出的时候触发 } catch (Exception ex) { LogNet?.WriteException(StringResources.SocketEndReceiveException, ex); //重新接收,此处已经排除掉了对象释放的异常 RefreshReceive(); } finally { //state = null; } } }
/// <summary> /// 表格数据 /// </summary> /// <returns></returns> public ActionResult List(int limit, int page, string houseNo, string OrderType) { T_Interface_Func TIF = new T_Interface_Func(); string json = ""; List <Kanban> kanbansOrder = new List <Kanban>(); var orderByEmergencyFlag = new List <Kanban>(); if (OrderType == "0")//出货单看板 { json = "{\"data_no\":\"" + houseNo + "\",\"VoucherType\":\"6000\"}"; string ERPJson = TIF.GetModelListByInterface(json); var returnKanban = JSONHelper.JsonToObject <ReturnKanban>(ERPJson); var kanbans = returnKanban.data == null ? new List <Kanban>() : returnKanban.data; LogNet.LogInfo("---------------------调用ERP接口:返回出货单看板参数:" + kanbans); orderByEmergencyFlag = kanbans.FindAll(x => x.EmergencyFlag == "True") .OrderBy(x => x.BusinessDate).ThenBy(x => x.TransportModeCode).ToList(); orderByEmergencyFlag.ForEach(x => x.BackColor = "red"); var orderByBusinessDate = kanbans.FindAll(x => !IsToday(x.BusinessDate) && Convert.ToDateTime(x.BusinessDate) < DateTime.Now && x.EmergencyFlag != "True").OrderBy(x => x.BusinessDate) .ThenBy(x => x.TransportModeCode).ToList(); orderByBusinessDate.ForEach(x => x.BackColor = "yellow"); var others = kanbans.FindAll(x => x.EmergencyFlag != "True" && (IsToday(x.BusinessDate) || Convert.ToDateTime(x.BusinessDate) > DateTime.Now)) .OrderBy(x => x.BusinessDate).ThenBy(x => x.TransportModeCode); kanbansOrder.AddRange(orderByEmergencyFlag); kanbansOrder.AddRange(orderByBusinessDate); kanbansOrder.AddRange(others); } else if (OrderType == "1")//形态转换看板 { json = "{\"data_no\":\"" + houseNo + "\",\"VoucherType\":\"6001\"}"; string ERPJson = TIF.GetModelListByInterface(json); var returnKanban = JSONHelper.JsonToObject <ReturnKanban>(ERPJson); var kanbans = returnKanban.data; if (kanbans == null) { kanbans = new List <Kanban>(); } LogNet.LogInfo("---------------------调用ERP接口:返回形态看板参数:" + kanbans); orderByEmergencyFlag = kanbans.FindAll(x => x.EmergencyFlag == "True" && x.Status != "Approved").OrderBy(x => x.BusinessDate).ToList(); orderByEmergencyFlag.ForEach(x => x.BackColor = "red"); var orderByBusinessDate = kanbans.FindAll(x => !IsToday(x.BusinessDate) && x.Status != "Approved" && Convert.ToDateTime(x.BusinessDate) < DateTime.Now && x.EmergencyFlag != "True").OrderBy(x => x.BusinessDate).ToList(); orderByBusinessDate.ForEach(x => x.BackColor = "yellow"); var orderByStatus = kanbans.FindAll(x => x.Status == "Approved") .OrderBy(x => x.BusinessDate).ToList(); orderByStatus.ForEach(x => x.BackColor = "blue"); var others = kanbans.FindAll(x => x.EmergencyFlag != "True" && (IsToday(x.BusinessDate) || Convert.ToDateTime(x.BusinessDate) > DateTime.Now) && x.Status != "Approved").OrderBy(x => x.BusinessDate); kanbansOrder.AddRange(orderByEmergencyFlag); kanbansOrder.AddRange(orderByBusinessDate); kanbansOrder.AddRange(others); kanbansOrder.AddRange(orderByStatus); } else if (OrderType == "2") { } else { } //发货看板赋值 var datas = new List <Kanban>(); if (orderByEmergencyFlag.Count() >= limit || page == 1) { datas = kanbansOrder.Take(limit).ToList(); } else { var pageDatas = kanbansOrder.Skip(limit * (page - 1)).Take(limit).ToList(); datas.AddRange(orderByEmergencyFlag); datas.AddRange(pageDatas.Take(limit - orderByEmergencyFlag.Count())); } if (OrderType == "0") { datas.ForEach(x => { var details = new TaskDetailsService().GetList(y => y.ERPVOUCHERNO == x.DocNo); var taskTran = new TasktransService() .GetList(z => z.ERPVOUCHERNO == x.DocNo && z.TASKTYPE == 2).FirstOrDefault(); x.SHELVEQTY = details.Sum(a => a.UNSHELVEQTY); x.CREATER = taskTran == null ? "" : taskTran.CREATER; }); } var jsonReturn = new { Result = 1, ResultValue = (datas == null || datas.Count() == 0) ? "没有符合条件的数据" : "", Data = datas, PageData = new { totalCount = kanbansOrder.Count(), pageSize = limit, currentPage = page, totalPages = kanbansOrder.Count() % limit > 0 ? (Math.Floor(Convert.ToDouble(kanbansOrder.Count() / limit)) + 1) : (kanbansOrder.Count() / limit) } }; return(Json(jsonReturn, JsonRequestBehavior.AllowGet)); }
/// <summary> /// 登录的回调方法 /// </summary> /// <param name="obj">传入的异步对象</param> protected override void ThreadPoolLogin(object obj) { if (obj is Socket socket) { // 注册包 // 0x48 0x73 0x6E 0x00 0x17 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x39 0x30 0x31 0x00 0x00 0x00 0x00 0x00 0x00 0xC0 0xA8 0x00 0x01 0x17 0x10 // +------------+ +--+ +--+ +----------------------------------------------------+ +---------------------------+ +-----------------+ +-------+ // + 固定消息头 +备用 长度 DTU码 12345678901 (唯一标识) 登录密码(不受信的排除) Ip:192.168.0.1 端口10000 // +------------+ +--+ +--+ +----------------------------------------------------+ +---------------------------+ +-----------------+ // 返回 // 0x48 0x73 0x6E 0x00 0x01 0x00 // +------------+ +--+ +--+ +--+ // 固定消息头 备用 长度 结果代码 // 结果代码 // 0x00: 登录成功 // 0x01: DTU重复登录 // 0x02: DTU禁止登录 // 0x03: 密码验证失败 OperateResult <AlienMessage> check = ReceiveMessage(socket, 5000, new AlienMessage( )); if (!check.IsSuccess) { return; } if (check.Content.HeadBytes[4] != 0x17 || check.Content.ContentBytes.Length != 0x17) { socket?.Close( ); LogNet?.WriteWarn(ToString( ), "Length Check Failed"); return; } // 密码验证 bool isPasswrodRight = true; for (int i = 0; i < password.Length; i++) { if (check.Content.ContentBytes[11 + i] != password[i]) { isPasswrodRight = false; break; } } string dtu = Encoding.ASCII.GetString(check.Content.ContentBytes, 0, 11).Trim( ); // 密码失败的情况 if (!isPasswrodRight) { OperateResult send = Send(socket, GetResponse(StatusPasswodWrong)); if (send.IsSuccess) { socket?.Close( ); } LogNet?.WriteWarn(ToString( ), "Login Password Wrong, Id:" + dtu); return; } AlienSession session = new AlienSession( ) { DTU = dtu, Socket = socket, }; // 检测是否禁止登录 if (!IsClientPermission(session)) { OperateResult send = Send(socket, GetResponse(StatusLoginForbidden)); if (send.IsSuccess) { socket?.Close( ); } LogNet?.WriteWarn(ToString( ), "Login Forbidden, Id:" + session.DTU); return; } // 检测是否重复登录,不重复的话,也就是意味着登录成功了 if (IsClientOnline(session)) { OperateResult send = Send(socket, GetResponse(StatusLoginRepeat)); if (send.IsSuccess) { socket?.Close( ); } LogNet?.WriteWarn(ToString( ), "Login Repeat, Id:" + session.DTU); return; } else { OperateResult send = Send(socket, GetResponse(StatusOk)); if (!send.IsSuccess) { return; } } // 触发上线消息 OnClientConnected?.Invoke(this, session); } }
/// <summary> /// 系统的登录方法 /// </summary> /// <param name="obj"></param> protected override void ThreadPoolLogin(object obj) { Socket socket = obj as Socket; try { //为了兼容原来旧的升级服务,暂时停止令牌功能 //接收令牌 2017-03-14 10:02:20 //InfoTcp infoTcp = new InfoTcp() //{ // Worksocket = socket, //}; // //ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadPoolCheckConnect), infoTcp); //try //{ // byte[] token = ReadFromSocket(socket, 16); // infoTcp.IsConnect = true; // if (!IsTwoBytesEquel(KeyToken.ToByteArray(), token)) // { // socket.Close(); // log_record.SaveNormal("接收到验证失败的连接"); // return; // } //} //catch (Exception ex) //{ // socket?.Close(); // log_record.SaveNormal("令牌接收出错:" + ex.Message); // return; //} byte[] ReceiveByte = NetSupport.ReadBytesFromSocket(socket, 4); int Protocol = BitConverter.ToInt32(ReceiveByte, 0); if (Protocol == 0x1001 || Protocol == 0x1002) { // 安装系统和更新系统 if (Protocol == 0x1001) { LogNet?.WriteInfo(LogHeaderText, StringResources.SystemInstallOperater + ((IPEndPoint)socket.RemoteEndPoint).Address.ToString()); } else { LogNet?.WriteInfo(LogHeaderText, StringResources.SystemUpdateOperater + ((IPEndPoint)socket.RemoteEndPoint).Address.ToString()); } if (Directory.Exists(FileUpdatePath)) { string[] files = Directory.GetFiles(FileUpdatePath); List <string> Files = new List <string>(files); for (int i = Files.Count - 1; i >= 0; i--) { FileInfo finfo = new FileInfo(Files[i]); if (finfo.Length > 200000000) { Files.RemoveAt(i); } if (Protocol == 0x1002) { if (finfo.Name == "软件自动更新.exe") { Files.RemoveAt(i); } } } files = Files.ToArray(); socket.BeginReceive(new byte[4], 0, 4, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket); socket.Send(BitConverter.GetBytes(files.Length)); for (int i = 0; i < files.Length; i++) { // 传送数据包含了本次数据大小,文件数据大小,文件名(带后缀) FileInfo finfo = new FileInfo(files[i]); string fileName = finfo.Name; byte[] ByteName = Encoding.Unicode.GetBytes(fileName); int First = 4 + 4 + ByteName.Length; byte[] FirstSend = new byte[First]; FileStream fs = new FileStream(files[i], FileMode.Open, FileAccess.Read); Array.Copy(BitConverter.GetBytes(First), 0, FirstSend, 0, 4); Array.Copy(BitConverter.GetBytes((int)fs.Length), 0, FirstSend, 4, 4); Array.Copy(ByteName, 0, FirstSend, 8, ByteName.Length); socket.Send(FirstSend); Thread.Sleep(10); byte[] buffer = new byte[4096]; int sended = 0; while (sended < fs.Length) { int count = fs.Read(buffer, 0, 4096); socket.Send(buffer, 0, count, SocketFlags.None); sended += count; } fs.Close(); fs.Dispose(); Thread.Sleep(20); } } } else { // 兼容原先版本的更新,新的验证方式无需理会 socket.Send(BitConverter.GetBytes(10000f)); Thread.Sleep(20); socket?.Close(); } } catch (Exception ex) { Thread.Sleep(20); socket?.Close(); LogNet?.WriteException(LogHeaderText, StringResources.FileSendClientFailed, ex); } }
private void ModbusDataReveiveCallback(IAsyncResult ar) { if (ar.AsyncState is ModBusState state) { try { state.ContentReceivedLength += state.WorkSocket.EndReceive(ar); if (state.ContentReceivedLength < state.Content.Length) { // 数据不够,继续接收 state.WorkSocket.BeginReceive(state.Content, state.ContentReceivedLength, state.Content.Length - state.ContentReceivedLength, SocketFlags.None, new AsyncCallback(ModbusDataReveiveCallback), state); return; } } catch (Exception ex) { // 关闭连接,记录日志 state.WorkSocket?.Close( ); LogNet?.WriteException(ToString(), $"客户端 [ {state.IpEndPoint} ] 下线,内容数据接收失败!", ex); return; } // 数据接收完成 // 内容接收完成,所有的数据接收结束 byte[] data = new byte[state.HeadByte.Length + state.Content.Length]; state.HeadByte.CopyTo(data, 0); state.Content.CopyTo(data, state.HeadByte.Length); state.Clear( ); byte[] modbusCore = ModbusTcpTransModbusCore(data); if (!CheckModbusMessageLegal(modbusCore)) { // 指令长度验证错误,关闭网络连接 state.WorkSocket?.Close( ); LogNet?.WriteError(ToString( ), $"客户端 [ {state.IpEndPoint} ] 下线,消息长度检查失败!"); return; } // 需要回发消息 byte[] copy = ModbusCoreTransModbusTcp(ReadFromModbusCore(modbusCore), data); try { // 管他是什么,先开始数据接收 // state.WorkSocket?.Close(); state.WorkSocket.BeginReceive(state.HeadByte, 0, 6, SocketFlags.None, new AsyncCallback(ModbusHeadReveiveCallback), state); } catch (Exception ex) { state.WorkSocket?.Close( ); LogNet?.WriteException(ToString( ), $"客户端 [ {state.IpEndPoint} ] 异常下线,重新接收消息失败!", ex); return; } // 回发数据,先获取发送锁 state.hybirdLock.Enter( ); try { state.WorkSocket.BeginSend(copy, 0, size: copy.Length, socketFlags: SocketFlags.None, callback: new AsyncCallback(DataSendCallBack), state: state); } catch (Exception ex) { state.WorkSocket?.Close( ); state.hybirdLock.Leave( ); LogNet?.WriteException(ToString( ), $"客户端 [ {state.IpEndPoint} ] 异常下线,开始回发消息失败!", ex); return; } // 通知处理消息 if (IsStarted) { OnDataReceived?.Invoke(data); } } }
/// <summary> /// 根据指令来读取设备的信息,如果命令数据为空,则传入null即可,注意,所有的命令不带换行符 /// </summary> /// <param name="command">命令的内容</param> /// <param name="commandData">命令数据内容</param> /// <returns>最终的结果内容,需要对IsSuccess进行验证</returns> public OperateResult <string> ReadByCommand(string command, string commandData) { InteractiveLock.Enter( ); // 获取有用的网络通道,如果没有,就建立新的连接 OperateResult <Socket> resultSocket = GetAvailableSocket( ); if (!resultSocket.IsSuccess) { IsSocketError = true; if (AlienSession != null) { AlienSession.IsStatusOk = false; } InteractiveLock.Leave( ); return(OperateResult.CreateFailedResult <string>(resultSocket)); } // 先发送命令 string sendCommand = string.IsNullOrEmpty(commandData) ? $"HOSTCTRL_REQUEST {command} 0\r\n" : $"HOSTCTRL_REQUEST {command} {commandData.Length}\r\n"; OperateResult <string> readCommand = ReadFromCoreServer(resultSocket.Content, sendCommand); if (!readCommand.IsSuccess) { IsSocketError = true; if (AlienSession != null) { AlienSession.IsStatusOk = false; } InteractiveLock.Leave( ); return(OperateResult.CreateFailedResult <string>(readCommand)); } // 检查命令是否返回成功的状态 if (!readCommand.Content.StartsWith("OK:")) { if (!isPersistentConn) { resultSocket.Content?.Close( ); } InteractiveLock.Leave( ); return(new OperateResult <string>(readCommand.Content.Remove(readCommand.Content.Length - 2))); } // 在必要的情况下发送命令数据 if (!string.IsNullOrEmpty(commandData)) { byte[] send2 = Encoding.ASCII.GetBytes($"{commandData}\r"); LogNet?.WriteDebug(ToString( ), StringResources.Language.Send + " : " + BasicFramework.SoftBasic.ByteToHexString(send2, ' ')); OperateResult sendResult2 = Send(resultSocket.Content, send2); if (!sendResult2.IsSuccess) { resultSocket.Content?.Close( ); IsSocketError = true; if (AlienSession != null) { AlienSession.IsStatusOk = false; } InteractiveLock.Leave( ); return(OperateResult.CreateFailedResult <string>(sendResult2)); } } // 接收数据信息,先接收到\r为止,再根据实际情况决定是否接收\r OperateResult <byte[]> resultReceive2 = NetSupport.ReceiveCommandLineFromSocket(resultSocket.Content, (byte)'\r'); if (!resultReceive2.IsSuccess) { IsSocketError = true; if (AlienSession != null) { AlienSession.IsStatusOk = false; } InteractiveLock.Leave( ); return(OperateResult.CreateFailedResult <string>(resultReceive2)); } string commandDataReturn = Encoding.ASCII.GetString(resultReceive2.Content); if (commandDataReturn.StartsWith("ERROR:")) { if (!isPersistentConn) { resultSocket.Content?.Close( ); } InteractiveLock.Leave( ); NetSupport.ReadBytesFromSocket(resultSocket.Content, 1); return(new OperateResult <string>(commandDataReturn)); } else if (commandDataReturn.StartsWith("0000\r")) { if (!isPersistentConn) { resultSocket.Content?.Close( ); } NetSupport.ReadBytesFromSocket(resultSocket.Content, 1); InteractiveLock.Leave( ); return(OperateResult.CreateSuccessResult("0000")); } else { if (!isPersistentConn) { resultSocket.Content?.Close( ); } InteractiveLock.Leave( ); return(OperateResult.CreateSuccessResult(commandDataReturn.Remove(commandDataReturn.Length - 1))); } }