Пример #1
0
 /// <summary>
 /// Deserializes the specified message.
 /// </summary>
 /// <param name="system">The system.</param>
 /// <param name="messageProtocol">The message protocol.</param>
 /// <returns>System.Object.</returns>
 public static object Deserialize(ActorSystem system, SerializedMessage messageProtocol)
 {
     return system.Serialization.Deserialize(
         messageProtocol.Message.ToByteArray(),
         messageProtocol.SerializerId,
         messageProtocol.HasMessageManifest ? messageProtocol.MessageManifest.ToStringUtf8() : null);
 }
Пример #2
0
 public Message(IInternalActorRef recipient, Address recipientAddress, SerializedMessage serializedMessage, IActorRef senderOptional = null, SeqNo seq = null)
 {
     Seq = seq;
     SenderOptional = senderOptional;
     SerializedMessage = serializedMessage;
     RecipientAddress = recipientAddress;
     Recipient = recipient;
 }
Пример #3
0
 /// <summary>
 /// Deserializes the specified message.
 /// </summary>
 /// <param name="system">The system.</param>
 /// <param name="messageProtocol">The message protocol.</param>
 /// <returns>System.Object.</returns>
 public static object Deserialize(ActorSystem system, SerializedMessage messageProtocol)
 {
     Type type = messageProtocol.HasMessageManifest
         ? Type.GetType(messageProtocol.MessageManifest.ToStringUtf8())
         : null;
     var message = system.Serialization.Deserialize(messageProtocol.Message.ToByteArray(),
         messageProtocol.SerializerId, type);
     return message;
 }
 public void Setup(BenchmarkContext context)
 {
     _actorSystem = ActorSystem.Create("MessageDispatcher" + Counter.GetAndIncrement(), RemoteHocon);
     _systemAddress = RARP.For(_actorSystem).Provider.DefaultAddress;
     _inboundMessageDispatcherCounter = context.GetCounter(MessageDispatcherThroughputCounterName);
     _message = SerializedMessage.CreateBuilder().SetSerializerId(0).SetMessage(ByteString.CopyFromUtf8("foo")).Build();
     _dispatcher = new DefaultMessageDispatcher(_actorSystem, RARP.For(_actorSystem).Provider, _actorSystem.Log);
     _targetActorRef = new BenchmarkActorRef(_inboundMessageDispatcherCounter, RARP.For(_actorSystem).Provider);
 }
Пример #5
0
        static IPipe <SendContext> CreateMessageContext(SerializedMessage message, Uri sourceAddress, PerformContext performContext, string jobKey = null)
        {
            IPipe <SendContext> sendPipe = Pipe.New <SendContext>(x =>
            {
                x.UseExecute(context =>
                {
                    if (!string.IsNullOrEmpty(jobKey))
                    {
                        context.Headers.Set(MessageHeaders.QuartzTriggerKey, jobKey);
                    }
                    context.Headers.Set(MessageHeaders.Quartz.Scheduled, performContext.BackgroundJob.CreatedAt.ToString("O"));
                    context.Headers.Set(MessageHeaders.Quartz.Sent, ((DateTime)InVar.Timestamp).ToString("O"));
                });
            });

            return(new SerializedMessageContextAdapter(sendPipe, message, sourceAddress));
        }
Пример #6
0
        public static bool TryReceiveMessage(this IReceivingSocket socket, out SerializedMessage message)
        {
            var mqMessage = new NetMQMessage();

            message = default(SerializedMessage);

            if (!socket.TryReceiveMultipartMessage(ref mqMessage, 2))
            {
                return(false);
            }

            var route = mqMessage[0].ConvertToString();
            var value = mqMessage[1].Buffer;

            message = new SerializedMessage(route, value);
            return(true);
        }
Пример #7
0
 private bool TryGetNextElementFromRereadMessage(out T element)
 {
     if (this.currentRereadMessageEnumerator != null)
     {
         // Otherwise, if we are current processing a spilled message, return messages from that.
         element = this.currentRereadMessageEnumerator.Current;
         if (!this.currentRereadMessageEnumerator.MoveNext())
         {
             this.currentRereadMessageEnumerator.Dispose();
             this.currentRereadMessageEnumerator = null;
             this.currentRereadMessage.Dispose();
             this.currentRereadMessage = null;
         }
         return(true);
     }
     return(TryGetNextElementByRereadingAnotherMessage(out element));
 }
Пример #8
0
 public void Write(SerializedMessage message)
 {
     if (this.typedBuffer.Free > 0)
     {
         // Attempt to process the records in memory (but may spill some if there is no capacity).
         foreach (T record in this.decoder.Elements(message))
         {
             this.Write(record);
         }
     }
     else
     {
         // Write the message directly to the file.
         MessageHeader.WriteHeaderToBuffer(this.rereadMessageHeaderBuffer, 0, message.Header, this.headerSerializer);
         this.spillStream.Write(this.rereadMessageHeaderBuffer, 0, this.rereadMessageHeaderBuffer.Length);
         this.spillStream.Write(message.Body.Buffer, message.Body.CurrentPos, message.Body.End - message.Body.CurrentPos);
     }
 }
Пример #9
0
        public void WorkerLoopWhenQueueContainsMessage()
        {
            // arrange
            var connection = new Mock <IConnection>();
            var worker     = new MessageSender(connection.Object);
            var message    = new SerializedMessage("TestRoute", new byte[] { 1, 2, 3 });

            // act
            worker.SendMessage(message);
            var firstProcessing  = worker.DoWork();
            var secondProcessing = worker.DoWork();

            // assert
            Assert.IsTrue(firstProcessing);
            Assert.IsFalse(secondProcessing);

            connection.Verify(x => x.SendMessage(message), Times.Once);
        }
Пример #10
0
        public void SerializedMessageReceived(SerializedMessage serializedMessage, ReturnAddress from)
        {
            System.Diagnostics.Debug.Assert(this.AvailableEntrancy >= -1);
            if (this.decoder == null)
            {
                this.decoder = new AutoSerializedMessageDecoder <S, T>(this.Vertex.SerializationFormat);
            }

            if (this.loggingEnabled)
            {
                this.LogMessage(serializedMessage);
            }

            foreach (Message <S, T> message in this.decoder.AsTypedMessages(serializedMessage))
            {
                this.OnReceive(message, from);
                message.Release();
            }
        }
Пример #11
0
        public void OnException()
        {
            // arrange
            var connection = new Mock <IConnection>();

            connection.Setup(x => x.SendMessage(It.IsAny <SerializedMessage>())).Throws <Exception>();

            var worker  = new MessageSender(connection.Object);
            var message = new SerializedMessage("TestRoute", new byte[] { 1, 2, 3 });

            // act
            worker.SendMessage(message);

            // assert
            Assert.Throws <ConnectionException>(() =>
            {
                worker.DoWork();
            });
        }
        public void OnException()
        {
            // arrange
            var serializedMessage = new SerializedMessage("OutcomingRoute", new byte[4]);

            var dataContract = new Mock <IDataContractOperations>();

            dataContract.Setup(x => x.Deserialize(serializedMessage)).Throws <Exception>();

            var worker = new MessageDeserializer(dataContract.Object);

            // act
            worker.DeserializeMessage(serializedMessage);

            // assert
            Assert.Throws <SerializationException>(() =>
            {
                worker.DoWork();
            });
        }
Пример #13
0
        private void UdpReceiveThread(IPEndPoint multicastGroupAddress)
        {
            Tracing.Trace("@UdpReceiveThread");
            IPEndPoint from = multicastGroupAddress;
            MessageHeader header = default(MessageHeader);
            //int count = 0;

            this.startCommunicatingEvent.WaitOne();

            while (true)
            {
                byte[] bytes = this.udpClient.Receive(ref from);

                Tracing.Trace("Recv");

                MessageHeader.ReadHeaderFromBuffer(bytes, 0, ref header, this.HeaderSerializer);
                //Console.Error.WriteLine("UdpReceiveThread: got {0} bytes from {1}. Sequence number = {2}, count = {3}", bytes.Length, from, header.SequenceNumber, count++);

                SerializedMessage message = new SerializedMessage(0, header, new RecvBuffer(bytes, MessageHeader.SizeOf, bytes.Length));
                bool success = this.AttemptDelivery(message, 0);
                Debug.Assert(success);
            }
        }
        public void WorkerLoopWhenSingleMessage()
        {
            // arrange
            var message = new SerializedMessage("TestRoute", new byte[] { 1, 2, 3 });
            SerializedMessage?messageFromEvent = null;

            var connection = new Mock <IConnection>();

            connection.Setup(x => x.TryReceiveMessage(out message)).Returns(true);

            var worker = new MessageReveiver(connection.Object);

            worker.OnNewMessage += m => messageFromEvent = m;

            // act
            var messageProcessed = worker.DoWork();

            // assert
            Assert.IsTrue(messageProcessed);
            Assert.AreEqual(message, messageFromEvent);

            connection.Verify(x => x.TryReceiveMessage(out message), Times.Once);
        }
Пример #15
0
        private bool AttemptDelivery(SerializedMessage message, int peerID = -1)
        {
            int graphId = message.Header.ChannelID >> 16;
            int channelId = message.Header.ChannelID & 0xFFFF;                    

            if (message.Header.DestVertexID == -1)
            {
                if (message.Header.ChannelID < 0 || this.localProcessID < 0)    // debug check
                    throw new Exception("This shouldn't happen");
                    
                // Special-cased logic for the progress channel, where we know that each process uses its process ID as the vertex ID.
                try
                {
                    this.graphmailboxes[graphId][channelId][this.localProcessID].DeliverSerializedMessage(message, new ReturnAddress(peerID, message.Header.FromVertexID));
                }
                catch (Exception)
                {
                    Console.Error.WriteLine("AttemptDelivery of progress message on ChannelId={0}, localProcessID={1}",
                        message.Header.ChannelID, this.localProcessID);
                    Console.Error.WriteLine("{0} mailboxes currently exist", "some");//this.mailboxes.Count);
                    System.Environment.Exit(-1);
                }

                return true;
            }
            else if (graphId >= this.graphmailboxes.Count ||
                this.graphmailboxes[graphId] == null ||
                channelId >= this.graphmailboxes[graphId].Count ||
                this.graphmailboxes[graphId][channelId] == null ||
                message.Header.DestVertexID >= this.graphmailboxes[graphId][channelId].Count ||
                this.graphmailboxes[graphId][channelId][message.Header.DestVertexID] == null)
            {
                Console.Error.WriteLine("Graphs: {0}/{1}", graphId, this.graphmailboxes.Count);
                throw new InvalidOperationException(String.Format("Failed delivery attempt"));

#if false
                to {0}:{1} (#channels = {2}, #vertices = {3}) from {4}",
Пример #16
0
        private bool TryReadNextMessage()
        {
            MessageHeader nextMessageHeader = default(MessageHeader);
            int           bytesRead         = this.consumeStream.Read(this.rereadMessageHeaderBuffer, 0, this.rereadMessageHeaderBuffer.Length);

            if (bytesRead < this.rereadMessageHeaderBuffer.Length)
            {
                // Reset to the start of a new message.
                this.consumeStream.Seek(-bytesRead, SeekOrigin.Current);
                return(false);
            }

            MessageHeader.ReadHeaderFromBuffer(this.rereadMessageHeaderBuffer, 0, ref nextMessageHeader, headerSerializer);

            if (nextMessageHeader.Type == SerializedMessageType.CheckpointData)
            {
                // Skip this because we have already buffered these elements in memory.
                this.consumeStream.Seek(nextMessageHeader.Length, SeekOrigin.Current);
                Console.Error.WriteLine("Skipping a log message of length {0}", nextMessageHeader.Length);
                return(TryReadNextMessage());
            }

            bytesRead = this.consumeStream.Read(this.rereadMessageBodyBuffer, 0, nextMessageHeader.Length);
            if (bytesRead < nextMessageHeader.Length)
            {
                // Reset to the start of a new message.
                this.consumeStream.Seek(-(bytesRead + MessageHeader.SizeOf), SeekOrigin.Current);
                return(false);
            }

            RecvBuffer messageBody = new RecvBuffer(this.rereadMessageBodyBuffer, 0, nextMessageHeader.Length);

            this.currentRereadMessage           = new SerializedMessage(-1, nextMessageHeader, messageBody);
            this.currentRereadMessageEnumerator = this.decoder.Elements(currentRereadMessage).GetEnumerator();
            this.currentRereadMessageEnumerator.MoveNext();
            return(true);
        }
        public void EventDeserialization()
        {
            // arrange
            var eventRoute = new Route("EventRoute", typeof(void));

            var configuration = new Mock <IDataContractAccess>();

            configuration.Setup(x => x.Routes).Returns(new List <Route> {
                eventRoute
            });
            configuration.Setup(x => x.Serializers).Returns(new List <Serializer>());
            configuration.Setup(x => x.Subscribers).Returns(new List <Subscriber>());

            var contract          = new DataContractManager(configuration.Object);
            var serializedMessage = new SerializedMessage("EventRoute", new byte[0]);

            // act
            var message = contract.Deserialize(serializedMessage);

            // assert
            var expectedMessage = new Message("EventRoute", null);

            Assert.AreEqual(expectedMessage, message);
        }
 private void AssertMessageSerializedCorrectly(SerializedMessage message, byte[] expectedBody, string expectedMessageType, string expectedCorrelationId)
 {
     Assert.Equal(message.Body, expectedBody);                              //, "Serialized message body does not match expected value");
     Assert.Equal(message.Properties.Type, expectedMessageType);            //, "Serialized message type does not match expected value");
     Assert.Equal(message.Properties.CorrelationId, expectedCorrelationId); //, "Serialized message correlation id does not match expected value");
 }
 private void AssertMessageSerializedCorrectly(SerializedMessage message, byte[] expectedBody, string expectedMessageType, string expectedCorrelationId)
 {
     Assert.That(message.Body, Is.EqualTo(expectedBody), "Serialized message body does not match expected value");
     Assert.That(message.Properties.Type, Is.EqualTo(expectedMessageType), "Serialized message type does not match expected value");
     Assert.That(message.Properties.CorrelationId, Is.EqualTo(expectedCorrelationId), "Serialized message correlation id does not match expected value");
 }
Пример #20
0
 public void SerializedMessageReceived(SerializedMessage message, RemotePostbox sender)
 {
     throw new NotImplementedException();
 }
Пример #21
0
 public bool TryReceiveMessage(out SerializedMessage message)
 {
     lock (_socketLock)
         return(Socket.TryReceiveMessage(out message));
 }
Пример #22
0
 public void SendMessage(SerializedMessage message)
 {
     lock (_socketLock)
         Socket.SendMessage(message);
 }
Пример #23
0
        public void SerializedMessageReceived(SerializedMessage message, RemotePostbox from)
        {
            System.Diagnostics.Debug.Assert(this.AvailableEntrancy >= -1);
            if (this.decoder == null)
            {
                this.decoder = new AutoSerializedMessageDecoder <S, T>();
            }

            if (this.loggingEnabled)
            {
                this.LogMessage(message);
            }
            foreach (Pair <S, T> record in this.decoder.Elements(message))
            {
                this.Buffer.payload[this.Buffer.length++] = record;
                if (this.Buffer.length == this.Buffer.payload.Length)
                {
                    var temp = Buffer;
                    Buffer.Disable();

                    if (SpareBuffers.Count > 0)
                    {
                        Buffer = SpareBuffers.Dequeue();
                    }
                    else
                    {
                        Buffer.Enable();
                    }

                    this.MessageReceived(temp, from);

                    temp.length = 0;
                    SpareBuffers.Enqueue(temp);

                    System.Diagnostics.Debug.Assert(this.Buffer.length == 0);
                    //this.Buffer.length = 0;
                }
            }

            if (this.Buffer.length > 0)
            {
                var temp = Buffer;
                Buffer.Disable();

                if (SpareBuffers.Count > 0)
                {
                    Buffer = SpareBuffers.Dequeue();
                }
                else
                {
                    Buffer.Enable();
                }

                this.MessageReceived(temp, from);

                temp.length = 0;
                SpareBuffers.Enqueue(temp);

                System.Diagnostics.Debug.Assert(this.Buffer.length == 0);
                //this.Buffer.length = 0;
            }
        }
 public SerializedMessageContextAdapter(IPipe <SendContext> pipe, SerializedMessage message, Uri sourceAddress)
 {
     _pipe          = pipe;
     _message       = message;
     _sourceAddress = sourceAddress;
 }
Пример #25
0
        public override ByteString ConstructMessage(Address localAddress, IActorRef recipient, SerializedMessage serializedMessage,
            IActorRef senderOption = null, SeqNo seqOption = null, Ack ackOption = null)
        {
            var ackAndEnvelopeBuilder = AckAndEnvelopeContainer.CreateBuilder();
            var envelopeBuilder = RemoteEnvelope.CreateBuilder().SetRecipient(SerializeActorRef(recipient.Path.Address, recipient));
            if (senderOption != null && senderOption.Path != null) { envelopeBuilder = envelopeBuilder.SetSender(SerializeActorRef(localAddress, senderOption)); }
            if (seqOption != null) { envelopeBuilder = envelopeBuilder.SetSeq((ulong)seqOption.RawValue); }
            if (ackOption != null) { ackAndEnvelopeBuilder = ackAndEnvelopeBuilder.SetAck(AckBuilder(ackOption)); }
            envelopeBuilder = envelopeBuilder.SetMessage(serializedMessage);
            ackAndEnvelopeBuilder = ackAndEnvelopeBuilder.SetEnvelope(envelopeBuilder);

            return ackAndEnvelopeBuilder.Build().ToByteString();
        }
Пример #26
0
        public void Dispatch(IInternalActorRef recipient, Address recipientAddress, SerializedMessage message,
            IActorRef senderOption = null)
        {
            var payload = MessageSerializer.Deserialize(system, message);
            Type payloadClass = payload == null ? null : payload.GetType();
            var sender = senderOption ?? system.DeadLetters;
            var originalReceiver = recipient.Path;

            var msgLog = string.Format("RemoteMessage: {0} to {1}<+{2} from {3}", payload, recipient, originalReceiver,
                sender);
            // message is intended for the RemoteDaemon, usually a command to create a remote actor
            if (recipient == remoteDaemon)
            {
                if (settings.UntrustedMode) log.Debug("dropping daemon message in untrusted mode");
                else
                {
                    if (settings.LogReceive) log.Debug("received daemon message [{0}]", msgLog);
                    remoteDaemon.Tell(payload);
                }
            }

            //message is intended for a local recipient
            else if ((recipient is ILocalRef || recipient is RepointableActorRef) && recipient.IsLocal)
            {
                if (settings.LogReceive) log.Debug("received local message [{0}]", msgLog);
                payload.Match()
                    .With<ActorSelectionMessage>(sel =>
                    {
                        var actorPath = "/" + string.Join("/", sel.Elements.Select(x => x.ToString()));
                        if (settings.UntrustedMode
                            && (!settings.TrustedSelectionPaths.Contains(actorPath)
                            || sel.Message is IPossiblyHarmful
                            || recipient != provider.Guardian))
                        {
                            log.Debug(
                                "operating in UntrustedMode, dropping inbound actor selection to [{0}], allow it" +
                                "by adding the path to 'akka.remote.trusted-selection-paths' in configuration",
                                actorPath);
                        }
                        else
                        {
                            //run the receive logic for ActorSelectionMessage here to make sure it is not stuck on busy user actor
                            ActorSelection.DeliverSelection(recipient, sender, sel);
                        }
                    })
                    .With<IPossiblyHarmful>(msg =>
                    {
                        if (settings.UntrustedMode)
                        {
                            log.Debug("operating in UntrustedMode, dropping inbound IPossiblyHarmful message of type {0}", msg.GetType());
                        }
                    })
                    .With<ISystemMessage>(msg => { recipient.Tell(msg); })
                    .Default(msg =>
                    {
                        recipient.Tell(msg, sender);
                    });
            }

            // message is intended for a remote-deployed recipient
            else if ((recipient is IRemoteRef || recipient is RepointableActorRef) && !recipient.IsLocal && !settings.UntrustedMode)
            {
                if (settings.LogReceive) log.Debug("received remote-destined message {0}", msgLog);
                if (provider.Transport.Addresses.Contains(recipientAddress))
                {
                    //if it was originally addressed to us but is in fact remote from our point of view (i.e. remote-deployed)
                    recipient.Tell(payload, sender);
                }
                else
                {
                    log.Error(
                        "Dropping message [{0}] for non-local recipient [{1}] arriving at [{2}] inbound addresses [{3}]",
                        payloadClass, recipient, recipientAddress, string.Join(",", provider.Transport.Addresses));
                }
            }
            else
            {
                log.Error(
                        "Dropping message [{0}] for non-local recipient [{1}] arriving at [{2}] inbound addresses [{3}]",
                        payloadClass, recipient, recipientAddress, string.Join(",", provider.Transport.Addresses));
            }
        }
Пример #27
0
 public abstract ByteString ConstructMessage(Address localAddress, IActorRef recipient,
                                             SerializedMessage serializedMessage, IActorRef senderOption = null, SeqNo seqOption = null, Ack ackOption = null);
Пример #28
0
            private static void Main(string[] args)
            {
                Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;

                try
                {
                    EngineSettings settings = new EngineSettings();

                    settings.TcpNoDelayOption         = false;
                    settings.SendLogoutOnInvalidLogon = true;
                    settings.ResendingQueueSize       = 0;
                    settings.Dialect = "ThroughputFixDictionary.xml";
                    settings.ValidateRequiredFields  = false;
                    settings.ValidateUnknownFields   = false;
                    settings.ValidateUnknownMessages = false;

                    Engine.Init(settings);

                    Dialect dialect = new Dialect("ThroughputDictionaryId");

                    string rawMessage =
                        "8=FIX.4.2\0019=3\00135=D\00149=OnixS\00156=CME\00134=01\00152=20120709-10:10:54\001" +
                        "11=90001008\00121=1\00155=ABC\00154=1\00138=100\00140=1\00160=20120709-10:10:54\00110=000\001";
                    rawMessage = rawMessage.Replace("\001", string.Empty + (char)0x01);

                    SerializedMessage order = new SerializedMessage(rawMessage);

                    const int listenPort = 4501;

                    const string senderCompId = "Acceptor";
                    const string targetCompId = "Initiator";

                    Session acceptor = new Session(senderCompId, targetCompId, dialect, false, SessionStorageType.MemoryBasedStorage);
                    acceptor.InboundApplicationMsgEvent += new InboundApplicationMsgEventHandler(InboundApplicationMsgEvent);
                    acceptor.ReuseIncomingMessage        = true;

                    acceptor.LogonAsAcceptor();

                    Session initiator = new Session(targetCompId, senderCompId, dialect, false, SessionStorageType.MemoryBasedStorage);
                    initiator.MessageGrouping      = 200;
                    initiator.ReuseIncomingMessage = true;

                    initiator.LogonAsInitiator("localhost", listenPort, 30);

                    for (int i = 0; i < WarmupNumberOfMessages; ++i)
                    {
                        initiator.Send(order);
                    }

                    long sendStart;
                    long sendFinish;

                    sendStart = TimestampHelper.Ticks;

                    for (int i = 0; i < NumberOfMessages; ++i)
                    {
                        initiator.Send(order);
                    }

                    sendFinish = TimestampHelper.Ticks;

                    ready.WaitOne();

                    acceptor.Logout();
                    initiator.Logout();

                    acceptor.Dispose();
                    initiator.Dispose();

                    double sendMessagesPerSec = 1000000.0 * NumberOfMessages / (sendFinish - sendStart);

                    double receiveMessagesPerSec = 1000000.0 * NumberOfMessages / (receiveFinish - receiveStart);

                    Console.WriteLine("\r\n");
                    Console.WriteLine("Throughput on send side: " + (int)sendMessagesPerSec + " (msg/sec)");
                    Console.WriteLine("Throughput on receive side: " + (int)receiveMessagesPerSec + " (msg/sec)");

                    Engine.Instance.Shutdown();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception: " + ex);
                }

                Console.WriteLine("Press <enter> for exit.");
                Console.ReadLine();
            }
Пример #29
0
 private static void AssertMessageSerializedCorrectly(SerializedMessage message, byte[] expectedBody, Action <MessageProperties> assertMessagePropertiesCorrect)
 {
     Assert.Equal(message.Body, expectedBody);           //, "Serialized message body does not match expected value");
     assertMessagePropertiesCorrect(message.Properties); //;
 }
Пример #30
0
 public void DeliverSerializedMessage(SerializedMessage message, ReturnAddress from)
 {
     throw new NotImplementedException("Attempted to deliver message from a remote sender to a remote recipient, which is not currently supported.");
 }
Пример #31
0
 public abstract ByteString ConstructMessage(Address localAddress, IActorRef recipient,
     SerializedMessage serializedMessage, IActorRef senderOption = null, SeqNo seqOption = null, Ack ackOption = null);
Пример #32
0
 public abstract void DeliverSerializedMessage(SerializedMessage message, ReturnAddress from);
 public void SendMessage(SerializedMessage message) => PublisherSocket.SendMessage(message);
Пример #34
0
 public void DeserializeMessage(SerializedMessage message) => _messageQueue.Enqueue(message);
Пример #35
0
        public override ByteString ConstructMessage(Address localAddress, IActorRef recipient, SerializedMessage serializedMessage,
                                                    IActorRef senderOption = null, SeqNo seqOption = null, Ack ackOption = null)
        {
            var ackAndEnvelopeBuilder = AckAndEnvelopeContainer.CreateBuilder();
            var envelopeBuilder       = RemoteEnvelope.CreateBuilder().SetRecipient(SerializeActorRef(recipient.Path.Address, recipient));

            if (senderOption != null && senderOption.Path != null)
            {
                envelopeBuilder = envelopeBuilder.SetSender(SerializeActorRef(localAddress, senderOption));
            }
            if (seqOption != null)
            {
                envelopeBuilder = envelopeBuilder.SetSeq((ulong)seqOption.RawValue);
            }
            if (ackOption != null)
            {
                ackAndEnvelopeBuilder = ackAndEnvelopeBuilder.SetAck(AckBuilder(ackOption));
            }
            envelopeBuilder       = envelopeBuilder.SetMessage(serializedMessage);
            ackAndEnvelopeBuilder = ackAndEnvelopeBuilder.SetEnvelope(envelopeBuilder);

            return(ackAndEnvelopeBuilder.Build().ToByteString());
        }
 public bool TryReceiveMessage(out SerializedMessage message) => SubscriberSocket.TryReceiveMessage(out message);
Пример #37
0
 private void AssertMessageSerializedCorrectly(SerializedMessage message, byte[] expectedBody, Action <MessageProperties> assertMessagePropertiesCorrect)
 {
     Assert.That(message.Body, Is.EqualTo(expectedBody), "Serialized message body does not match expected value");
     assertMessagePropertiesCorrect(message.Properties);
 }
Пример #38
0
            private static void Main(string[] args)
            {
                Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;

                try
                {
                    EngineSettings settings = new EngineSettings();

                    settings.SendLogoutOnInvalidLogon = true;
                    settings.ResendingQueueSize       = 0;
                    settings.Dialect = "LatencyFixDictionary.xml";
                    settings.ValidateRequiredFields  = false;
                    settings.ValidateUnknownFields   = false;
                    settings.ValidateUnknownMessages = false;

                    Engine.Init(settings);

                    Dialect dialect = new Dialect("LatencyDictionaryId");

                    string rawMessage = "8=FIX.4.2\0019=3\00135=D\00149=OnixS\00156=CME\00134=01\00152=20120709-10:10:54\00111=90001008\001109=ClientID\00121=1\00155=ABC\00154=1\00138=100\00140=1\00160=20120709-10:10:54\00110=000\001";
                    rawMessage = rawMessage.Replace("\001", string.Empty + (char)0x01);

                    // Please note that a Serialized Message is used here to facilitate the best possible latency.
                    SerializedMessage order = new SerializedMessage(rawMessage);

                    const int listenPort = 4501;

#if DEBUG
                    const int NumberOfMessages = 1000;
#else
                    const int NumberOfMessages = 50000;
#endif

                    marks = new SessionTimeMarks[NumberOfMessages];

                    const string senderCompId = "Acceptor";
                    const string targetCompId = "Initiator";

                    Session acceptor = new Session(senderCompId, targetCompId, dialect, false, SessionStorageType.MemoryBasedStorage);
                    acceptor.InboundApplicationMsgEvent += new InboundApplicationMsgEventHandler(InboundApplicationMsgEvent);
                    acceptor.BytesReceived       += new BytesReceivedEventHandler(acceptor_BytesReceived);
                    acceptor.ReuseIncomingMessage = true;

                    acceptor.LogonAsAcceptor();

                    Session initiator = new Session(targetCompId, senderCompId, dialect, false, SessionStorageType.MemoryBasedStorage);
                    initiator.MessageSending      += new MessageSendingEventHandler(OnMsgEvent);
                    initiator.ReuseIncomingMessage = true;

                    initiator.LogonAsInitiator("localhost", listenPort, 30);

                    active = true;

                    SerializedFieldRef clientIDRef = order.Find(FIXForge.NET.FIX.FIX42.Tags.ClientID);

                    if (clientIDRef == null)
                    {
                        throw new Exception("clientID field is not found");
                    }

                    SerializedFieldKey clientIDKey = order.AllocateKey(clientIDRef);

                    const string shortClientId = "ClientID";
                    const string LongClientId  = "ClientIDClientIDClientIDClientID";

                    for (int i = 0; i < NumberOfMessages; ++i)
                    {
                        ready.WaitOne();

                        TimestampHelper.GetTicks(ref marks[counter].SendStart);

                        order.Set(clientIDKey, i % 2 == 0 ? shortClientId : LongClientId);

                        initiator.Send(order);
                    }

                    ready.WaitOne();

                    active = false;

                    acceptor.Logout();
                    initiator.Logout();

                    acceptor.Dispose();
                    initiator.Dispose();

                    ReportSessionTimeMarksStatistics("Latency", marks, NumberOfMessages);

                    Engine.Instance.Shutdown();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception: " + ex);
                }

                Console.WriteLine("Press <enter> for exit.");
                Console.ReadLine();
            }