public void BytesToHexString() { var testArray = new byte[] { 1, 2, 3, 16, 17, 255 }; var hexString = HexFormatUtil.ToHexString(testArray); Assert.IsTrue(hexString == "01 02 03 10 11 FF"); }
/// <summary> /// Tries to send the given message to the currently connected partner /// </summary> /// <param name="buffer">The bytes to be sent</param> /// <returns>True when sending was successful</returns> public override async Task <bool> SendAsync(ArraySegment <byte> buffer) { buffer.MustNotBeDefault(nameof(buffer)); if (buffer.Count <= 0) { this.Log(LoggingMessageType.Error, "Unable to send message: Message is empty!"); return(false); } var currentClient = this.GetCurrentSendSocket(); if (currentClient == null) { this.Log(LoggingMessageType.Error, "Unable to send message: Connection is not established currently!"); return(false); } try { await currentClient.SendAsync(buffer, SocketFlags.None) .ConfigureAwait(false); if (this.IsLoggerSet) { this.Log( LoggingMessageType.Info, StringBuffer.Format("Sent {0} bytes: {1}", buffer.Count, HexFormatUtil.ToHexString(buffer))); } return(true); } catch (Exception sendException) { if (this.IsLoggerSet) { this.Log( LoggingMessageType.Info, StringBuffer.Format("Error while sending message: {0}", sendException.Message)); } return(false); } }
/// <inheritdoc /> public override Task <bool> SendAsync(ArraySegment <byte> buffer) { if ((buffer.Count <= 0) || (buffer.Array == null)) { this.Log(LoggingMessageType.Error, "Unable to send message: Message is empty!"); return(s_completedTaskFalse); } var serialPort = _serialPort; if (serialPort == null) { this.Log(LoggingMessageType.Error, "Unable to send message: Connection is not started!"); return(s_completedTaskFalse); } try { serialPort.Write(buffer.Array, buffer.Offset, buffer.Count); if (this.IsLoggerSet) { this.Log( LoggingMessageType.Info, StringBuffer.Format("Sent {0} bytes: {1}", buffer.Count, HexFormatUtil.ToHexString(buffer))); } return(s_completedTaskTrue); } catch (Exception ex) { if (this.IsLoggerSet) { this.Log( LoggingMessageType.Info, StringBuffer.Format("Error while sending message: {0}", ex.Message)); } return(s_completedTaskFalse); } }
private void ProcessReceivedBytes(bool newConnection, byte[] buffer, int receivedBytesCount) { buffer.MustNotBeNull(nameof(buffer)); var receiveBuffer = new ArraySegment <byte>(buffer, 0, receivedBytesCount); // Log currently received bytes if (this.IsLoggerSet) { this.Log( LoggingMessageType.Info, StringBuffer.Format("Received {0} bytes: {1}", receiveBuffer.Count, HexFormatUtil.ToHexString(receiveBuffer))); } // Notify received bytes var messageRecognizer = this.MessageRecognizer; messageRecognizer?.OnReceivedBytes(newConnection, receiveBuffer); }