Example #1
0
        public async Task SendAsync <P>(ServiceBusMessage message, Reference <ReplyTask <P> > replyReference) where P : class
        {
            UdpClient udpSender = null;

            if (ServiceBusMessage.TO_ALL_NODES.Equals(message.ToNode))
            {
                udpSender = _senderClient;
            }
            else
            {
                var peerInfo = GetLocalService <IPeerManager>().Peers.Where(s => s.Name == message.ToNode).FirstOrDefault();

                if (peerInfo != null && peerInfo.IPAddresses.Length > 0)
                {
                    Interlocked.Increment(ref _sendAsyncReplyCount);

                    var peerAddress  = peerInfo.IPAddresses[0];
                    var senderClient = new UdpClient(peerAddress, _multicastPort);
                    udpSender = senderClient;
                }
                else
                {
                    throw new Exception("There is no known peer, or a known peer has no known ip addresses.");
                }
            }

            if (udpSender != null)
            {
                if (replyReference != null)
                {
                    lock (_outgoingMessages)
                    {
                        replyReference.Item = _outgoingMessages.First.Value.AddForMessage <P>(message);
                        message.MarkOriginatorRequiresReply();
                    }
                }

                Interlocked.Increment(ref _sendingAsync);

                message.SetSendTimeUTC(DateTime.UtcNow);
                var data = Root.ServiceBusInstance.GetLocalService <ISerializer>().Serialize(message);

                udpSender.SendAsync(data, data.Length).ContinueWith(
                    (task) =>
                {
                    if (task.Status != TaskStatus.RanToCompletion)
                    {
                        _serviceBusTracing.TraceEvent(TraceEventType.Warning, TRACEEVENT_SENDASYNC, "SendAsync {1} - {0} bytes.", task.Result, task.Status);
                        Interlocked.Increment(ref _sentAsyncFailed);
                    }
                    else
                    {
                        _serviceBusTracing.TraceEvent(TraceEventType.Verbose, TRACEEVENT_SENDASYNC, "SendAsync OK {0} bytes.", task.Result);
                        Interlocked.Increment(ref _sentAsyncOK);
                    }

                    _serviceBusTracing.TraceEvent(TraceEventType.Verbose, TRACEEVENT_SENDASYNC, "SendAsync {0} bytes.", task.Result);
                }
                    );
            }
            else
            {
                throw new Exception("There is no transport available to send this message on.");
            }
        }