Exemplo n.º 1
0
        /// <summary>
        ///     Process replies on the request socket.
        ///     Heartbeats, errors, and subscribing to real time data streams.
        /// </summary>
        private void RealTimeRequestSocketReceiveReady(object sender, NetMQSocketEventArgs e)
        {
            lock (realTimeRequestSocketLock)
            {
                string reply = realTimeRequestSocket?.ReceiveFrameString();

                if (reply == null)
                {
                    return;
                }

                DataRequestMessageType mesageTye = (DataRequestMessageType)BitConverter.ToInt16(realTimeRequestSocket.ReceiveFrameBytes(), 0);
                RealTimeDataRequest    request;
                switch (mesageTye)
                {
                case DataRequestMessageType.Pong:
                    lastHeartBeat = DateTime.Now;
                    break;

                case DataRequestMessageType.Error:

                    string error   = realTimeRequestSocket.ReceiveFrameString();
                    byte[] buffer1 = realTimeRequestSocket.ReceiveFrameBytes();

                    using (MemoryStream ms = new MemoryStream(buffer1))
                    {
                        request = MyUtils.ProtoBufDeserialize <RealTimeDataRequest>(ms);
                    }
                    // Error event
                    RaiseEvent(Error, this,
                               new ErrorArgs(-1, "Real time data request error: " + error, request.RequestID));
                    break;

                case DataRequestMessageType.Success:

                    byte[] buffer = realTimeRequestSocket.ReceiveFrameBytes();
                    using (MemoryStream ms = new MemoryStream(buffer))
                    {
                        request = MyUtils.ProtoBufDeserialize <RealTimeDataRequest>(ms);
                    }

                    lock (realTimeDataStreamsLock)
                    {
                        RealTimeDataStreams.Add(request);
                    }

                    realTimeDataSocket.Subscribe(BitConverter.GetBytes(request.Instrument.ID));
                    break;

                case DataRequestMessageType.RTDCanceled:

                    string symbol = realTimeRequestSocket.ReceiveFrameString();

                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        ///     Process replies on the request socket.
        ///     Heartbeats, errors, and subscribing to real time data streams.
        /// </summary>
        private void RealTimeRequestSocketReceiveReady(object sender, NetMQSocketEventArgs e)
        {
            lock (_realTimeRequestSocketLock)
            {
                using (var ms = new MemoryStream())
                {
                    var reply = _realTimeRequestSocket?.ReceiveFrameString();

                    if (reply == null)
                    {
                        return;
                    }

                    reply = _realTimeRequestSocket.ReceiveFrameString();

                    if (reply.Equals(MessageType.Pong, StringComparison.InvariantCultureIgnoreCase))
                    {
                        // Reply to heartbeat message
                        _lastHeartBeat = DateTime.Now;
                    }
                    else if (reply.Equals(MessageType.Error, StringComparison.InvariantCultureIgnoreCase))
                    {
                        // Something went wrong
                        // First the message
                        var error = _realTimeRequestSocket.ReceiveFrameString();
                        // Then the request
                        var buffer  = _realTimeRequestSocket.ReceiveFrameBytes();
                        var request = MyUtils.ProtoBufDeserialize <RealTimeDataRequest>(buffer, ms);
                        // Error event
                        RaiseEvent(Error, this, new ErrorArgs(-1, "Real time data request error: " + error, request.RequestID));
                    }
                    else if (reply.Equals(MessageType.Success, StringComparison.InvariantCultureIgnoreCase))
                    {
                        // Successful request to start a new real time data stream
                        // Receive the request
                        var buffer  = _realTimeRequestSocket.ReceiveFrameBytes();
                        var request = MyUtils.ProtoBufDeserialize <RealTimeDataRequest>(buffer, ms);
                        // Add it to the active streams
                        lock (_realTimeDataStreamsLock)
                        {
                            RealTimeDataStreams.Add(request);
                        }
                        // TODO: Solve issue with null request
                        // Request worked, so we subscribe to the stream
                        _realTimeDataSocket.Subscribe(BitConverter.GetBytes(request.Instrument.ID.Value));
                    }
                    else if (reply.Equals(MessageType.RTDCanceled, StringComparison.InvariantCultureIgnoreCase))
                    {
                        // Successful cancelation of a real time data stream
                        // Also receive the symbol
                        var symbol = _realTimeRequestSocket.ReceiveFrameString();
                        // Nothing to do?
                    }
                }
            }
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="callback">获取到一条数据的回调函数</param>
        public void GetMessage(Action <byte[]> callback)
        {
            Console.WriteLine("开始监听队列");
            var receiver = new DealerSocket($"@tcp://{_defaultConnectionString}:5557"); //接收消息

            while (true)                                                                //简单的监听loop
            {
                var message = receiver.ReceiveFrameBytes();                             //未接收到消息将阻塞线程
                GetMessageTimes++;
                callback(message);
            }
        }
Exemplo n.º 4
0
        public IMessageBroker Startup()
        {
            if (IsStarted)
            {
                return(this);
            }
            var cancellationTokenSource = _cancellationTokenSource = new CancellationTokenSource();

            _proxyTask = Task.Run(() =>
            {
                var address    = _configuration.GetAddress();
                var pubAddress = $"@{_configuration.Schema}://{address}:{_configuration.XPubPort}";
                var subAddress = $"@{_configuration.Schema}://{address}:{_configuration.XSubPort}";
#if DEBUG
                System.Diagnostics.Debug.WriteLine($"[{nameof( MessageBroker )}]XPub listening on: {pubAddress}");
                System.Diagnostics.Debug.WriteLine($"[{nameof( MessageBroker )}]XSub listening on: {subAddress}");
#endif
                using (var xpubSocket = new XPublisherSocket(pubAddress))
                    using (var xsubSocket = new XSubscriberSocket(subAddress))
                        using (var controlIn = new DealerSocket("@inproc://control-in"))
                            using (var controlOut = new DealerSocket("@inproc://control-out"))
                                using (var controlInRecv = new DealerSocket(">inproc://control-in"))
                                    using (var controlOutRecv = new DealerSocket(">inproc://control-out"))
                                    {
                                        Task.Run(() =>
                                        {
                                            while (!cancellationTokenSource.IsCancellationRequested)
                                            {
                                                try
                                                {
                                                    var topic           = controlInRecv.ReceiveFrameString();
                                                    var timestamp_bytes = controlInRecv.ReceiveFrameBytes();
                                                    var timestamp_int64 = BitConverter.ToInt64(timestamp_bytes, 0);
                                                    var timestamp       = new DateTimeOffset(timestamp_int64, TimeSpan.FromMinutes(0));
                                                    var message         = controlInRecv.ReceiveFrameString();
                                                    var wrapper         = new MessageWrapper(topic, message, timestamp);
                                                    Logger?.LogReceive(wrapper);
                                                }
                                                catch (System.ObjectDisposedException)
                                                {
                                                    return;
                                                }
                                            }
                                        }, cancellationTokenSource.Token);
                                        //proxy messages between frontend / backend
                                        var proxy = _proxy = new Proxy(xsubSocket, xpubSocket, controlIn, controlOut);
                                        //WARNING:blocks indefinitely.
                                        proxy.Start();
                                    }
            }, cancellationTokenSource.Token);
            return(this);
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            Console.WriteLine(args.Length);
            if (args.Length < 3)
            {
                Console.WriteLine("Requeries 3 arguments: WORLD_SOCKET CRANE_SOCKET SIM_ID");
                return;
            }
            var           worldSocketAddr = args[0];
            var           craneSocketAddr = args[1];
            var           identity        = new UTF8Encoding().GetBytes(args[2]);
            OptimizerType optType;

            if (args.Length > 3)
            {
                optType = OptimizerType.ModelBased;
            }
            else
            {
                optType = OptimizerType.RuleBased;
            }
            Console.WriteLine(optType);

            using (var worldSocket = new DealerSocket()) // bind
                using (var craneSocket = new DealerSocket())
                {
                    worldSocket.Options.Identity = identity;
                    craneSocket.Options.Identity = identity;
                    worldSocket.Connect(worldSocketAddr);
                    Console.WriteLine("Connected world");
                    craneSocket.Connect(craneSocketAddr);
                    Console.WriteLine("Connected crane");


                    while (true)
                    {
                        var world = World.Parser.ParseFrom(worldSocket.ReceiveFrameBytes());

                        var schedule = OptimizeCraneShedule(world, optType);
                        if (schedule != null)
                        {
                            schedule.SequenceNr = world.Crane.Schedule.SequenceNr;
                            Console.WriteLine(schedule);
                            var data = schedule.ToByteArray();
                            Console.WriteLine(data.Length);
                            var msg = new Msg();
                            msg.InitGC(data, data.Length);
                            craneSocket.Send(ref msg, false);
                        }
                    }
                }
        }
Exemplo n.º 6
0
        /// <summary>
        ///     Called when we get some sort of error reply
        /// </summary>
        private void HandleErrorReply()
        {
            // The request ID
            bool hasMore;
            var  buffer = _historicalDataSocket.ReceiveFrameBytes(out hasMore);

            if (!hasMore)
            {
                return;
            }
            var requestId = BitConverter.ToInt32(buffer, 0);

            // Remove from pending requests
            lock (_pendingHistoricalRequestsLock) {
                PendingHistoricalRequests.RemoveAll(x => x.RequestID == requestId);
            }
            // Finally the error message
            var message = _historicalDataSocket.ReceiveFrameString();

            // Raise the error event
            RaiseEvent(Error, this, new ErrorArgs(-1, message, requestId));
        }
Exemplo n.º 7
0
        /// <summary>
        ///     Handling replies to a data push, a historical data request, or an available data request
        /// </summary>
        private void HistoricalDataSocketReceiveReady(object sender, NetMQSocketEventArgs e)
        {
            lock (historicalDataSocketLock)
            {
                if (historicalDataSocket == null)
                {
                    return;
                }
                // 1st message part: what kind of stuff we're receiving
                DataRequestMessageType type = (DataRequestMessageType)BitConverter.ToInt16(historicalDataSocket.ReceiveFrameBytes(), 0);
                switch (type)
                {
                case DataRequestMessageType.Error:
                    HandleErrorReply();
                    break;

                case DataRequestMessageType.AvailableDataReply:
                    HandleAvailabledataReply();
                    break;

                case DataRequestMessageType.HistReply:
                    HandleHistoricalDataRequestReply();
                    break;

                case DataRequestMessageType.HistPushReply:
                    HandleDataPushReply();
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
        }