public void FullTest() { var message = new MessagePackage { SenderUID = 123, ReceiverUID = 789, MessageID = 6, Configuration = MessageConfigurationEnum.IsConfirmation, MessageBody = System.Text.Encoding.ASCII.GetBytes("One test!!") }; var messageBytes = message.GetMessage(); var messageBack = MessagePackage.Parse(messageBytes); Assert.Equal(message.SenderUID, messageBack.SenderUID); Assert.Equal(message.ReceiverUID, messageBack.ReceiverUID); Assert.Equal(message.MessageID, messageBack.MessageID); Assert.Equal(message.Configuration, messageBack.Configuration); Assert.Equal( System.Text.Encoding.ASCII.GetString(message.MessageBody), System.Text.Encoding.ASCII.GetString(messageBack.MessageBody)); }
public void Send(ushort receiverUID, byte[] messageBody, MessageArriveDelegate callBack = null) { var messsageID = _messageID++; var configuration = MessageConfigurationEnum.None; if (callBack != null) configuration |= MessageConfigurationEnum.NeedConfirmation; var package = new MessagePackage(_UID, receiverUID, messsageID, configuration, messageBody); var messageStore = new MessageStore { Package = package, Callback = callBack }; var time = new Timer(WaitingTimeoutCallback, messageStore, TimeOut, Timeout.Infinite); messageStore.TimeoutTimer = time; lock (_messageskLock) { var hasInStack = _messageStack .Where(ms => ms.Package.ReceiverUID == receiverUID); if (hasInStack.Any()) { _messageQueue.Add(messageStore); } else { _messageStack.Add(messageStore); } Monitor.Pulse(_messageskLock); } }
private void Receiver(MessagePackage package) { if (package.ReceiverUID != _UID) return; if ((package.Configuration & MessageConfigurationEnum.NeedConfirmation) != 0) { var packageConfirmation = new MessagePackage(_UID, package.SenderUID, package.MessageID, MessageConfigurationEnum.IsConfirmation, new byte[0]); var messageStack = new MessageStore { Package = packageConfirmation }; lock (_messageskLock) { _messageStack.Add(messageStack); Monitor.Pulse(_messageskLock); } } if ((package.Configuration & MessageConfigurationEnum.IsConfirmation) != 0) { MessageStore message; lock (_messageWaiting) { message = _messageWaiting .Where(s => s.Package.ReceiverUID == package.SenderUID && s.Package.MessageID == package.MessageID) .FirstOrDefault(); } if (message == null) { Task.Run(() => MessageArrive(MessageArriveCode.ConfirmationWithoutWaiting, package)); } else { lock (_messageWaiting) { _messageWaiting.Remove(message); } message.TimeoutTimer?.Dispose(); message.Callback?.Invoke(MessageArriveCode.Ok, message.Package); } } else { var hasQueue = _messageQueue .Where(s => s.Package.ReceiverUID == package.SenderUID) .FirstOrDefault(); if (hasQueue != null) { lock (_messageskLock) { _messageQueue.Remove(hasQueue); _messageStack.Add(hasQueue); Monitor.Pulse(_messageskLock); } } Task.Run(() => MessageArrive(MessageArriveCode.Ok, package)); } }