/// <summary> /// 发送报文,并获取响应报文 /// </summary> /// <param name="command"></param> /// <param name="lenght"></param> /// <returns></returns> public Result <byte[]> SendPackage(byte[] command, int lenght) { Result <byte[]> _SendPackage() { lock (this) { //从发送命令到读取响应为最小单元,避免多线程执行串数据(可线程安全执行) Result <byte[]> result = new Result <byte[]>(); //发送命令 socket.Send(command); //获取响应报文 var socketReadResul = SocketRead(socket, lenght); if (!socketReadResul.IsSucceed) { return(socketReadResul); } result.Value = socketReadResul.Value; return(result.EndTime()); } } try { var result = _SendPackage(); if (!result.IsSucceed) { WarningLog?.Invoke(result.Err, result.Exception); //如果出现异常,则进行一次重试 var conentResult = Connect(); if (!conentResult.IsSucceed) { return(new Result <byte[]>(conentResult)); } return(_SendPackage()); } else { return(result); } } catch (Exception ex) { WarningLog?.Invoke(ex.Message, ex); //如果出现异常,则进行一次重试 //重新打开连接 var conentResult = Connect(); if (!conentResult.IsSucceed) { return(new Result <byte[]>(conentResult)); } return(_SendPackage()); } }
/// <summary> /// 发送报文,并获取响应报文 /// </summary> /// <param name="command"></param> /// <returns></returns> public Result <byte[]> SendPackage(byte[] command) { //从发送命令到读取响应为最小单元,避免多线程执行串数据(可线程安全执行) lock (this) { Result <byte[]> result = new Result <byte[]>(); void _sendPackage() { socket.Send(command); var head = SocketRead(socket, 8); byte[] buffer = new byte[4]; buffer[0] = head[7]; buffer[1] = head[6]; buffer[2] = head[5]; buffer[3] = head[4]; //4-7是Length字段 表示其后所有字段的总长度 var contentLength = BitConverter.ToInt32(buffer, 0); var dataPackage = SocketRead(socket, contentLength); result.Value = head.Concat(dataPackage).ToArray(); } try { _sendPackage(); } catch (Exception ex) { WarningLog?.Invoke(ex.Message, ex); //如果出现异常,则进行一次重试 //重新打开连接 var conentResult = Connect(); if (!conentResult.IsSucceed) { return(new Result <byte[]>(conentResult)); } _sendPackage(); } return(result.EndTime()); } }
/// <summary> /// 发送报文,并获取响应报文 /// </summary> /// <param name="command"></param> /// <returns></returns> public Result <byte[]> SendPackage(byte[] command) { //从发送命令到读取响应为最小单元,避免多线程执行串数据(可线程安全执行) lock (this) { Result <byte[]> result = new Result <byte[]>(); void _sendPackage() { socket.Send(command); var head = SocketRead(socket, 24); var content = SocketRead(socket, GetContentLength(head)); result.Value = head.Concat(content).ToArray(); } try { _sendPackage(); } catch (Exception ex) { WarningLog?.Invoke(ex.Message, ex); //如果出现异常,则进行一次重试 //重新打开连接 var conentResult = Connect(); if (!conentResult.IsSucceed) { return(new Result <byte[]>(conentResult)); } _sendPackage(); } return(result.EndTime()); } }