コード例 #1
0
        public Socket_NetMQ(SocketType socketType)
        {
            switch (socketType)
            {
            case SocketType.Pub:
                innerSocket = innerContext.CreateSocket(NetMQ.ZmqSocketType.Pub);
                break;

            case SocketType.Pull:
                innerSocket = innerContext.CreateSocket(NetMQ.ZmqSocketType.Pull);
                break;

            case SocketType.Push:
                innerSocket = innerContext.CreateSocket(NetMQ.ZmqSocketType.Push);
                break;

            case SocketType.Sub:
                innerSocket = innerContext.CreateSocket(NetMQ.ZmqSocketType.Sub);
                break;

            default:
                throw new Exception("Non support SocketType.");
            }
            innerSocket.Options.TcpKeepalive         = true;
            innerSocket.Options.ReconnectInterval    = TimeSpan.FromMilliseconds(100);
            innerSocket.Options.ReconnectIntervalMax = TimeSpan.FromMilliseconds(8000);
            innerSocket.Options.Linger = TimeSpan.FromMilliseconds(0);
        }
コード例 #2
0
        public void Start()
        {
            this.Log().Info("启动状态计算服务");
            _context = NetMQContext.Create();
            _socket  = _context.CreateSocket(ZmqSocketType.Rep);
            _socket.Connect(ConfigurationManager.AppSettings["broker"]);
            _running = true;
            while (_running)
            {
                this.Log().Info("开始接收消息");
                var message = _socket.ReceiveString();
                this.Log().Info("接收消息:{" + message + "}");
                var taskMesg = JsonConvert.DeserializeObject <IndexTask>(message);

                var objType   = taskMesg.type;
                var objCode   = taskMesg.code;
                var cycleType = taskMesg.cycle;// (TechCycle)Enum.Parse(typeof(TechCycle), taskMesg.cycle, true);

                var tech = new TechCalculate(objType, cycleType, objCode, null);
                tech.CalculateState();

                this.Log().Info("处理完成:" + message);
                _socket.Send("处理完成:{" + message + "}");
            }
        }
コード例 #3
0
        public void TechTask()
        {
            using (NetMQContext _context = NetMQContext.Create())
            {
                using (NetMQSocket _socket = _context.CreateSocket(ZmqSocketType.Req))
                {
                    _socket.Connect(ConfigurationManager.AppSettings["broker"]);
                    while (true)
                    {
                        IndexTask task = null;
                        lock (this.TaskQueue)
                        {
                            if (this.TaskQueue.Count > 0)
                            {
                                task = this.TaskQueue.Dequeue();
                                this.Log().Info("remain:" + this.TaskQueue.Count);
                            }
                        }

                        if (task == null)
                        {
                            Thread.Sleep(5000);
                            break;
                        }
                        string msg      = JsonConvert.SerializeObject(task);
                        byte[] msgBytes = Encoding.UTF8.GetBytes(msg);
                        _socket.Send(msg);
                        this.Log().Info("send:{" + msg + "}");
                        string message = _socket.ReceiveString();
                        this.Log().Info("rcv:" + message);
                    }
                }
            }
        }
コード例 #4
0
        public void Start()
        {
            this.Log().Info("启动计算服务");
            _context = NetMQContext.Create();
            _socket  = _context.CreateSocket(ZmqSocketType.Rep);
            _socket.Connect(ConfigurationManager.AppSettings["broker"]);
            _running = true;
            while (_running)
            {
                this.Log().Info("开始接收消息");
                var message = _socket.ReceiveString();
                this.Log().Info("接收消息:{" + message + "}");
                var taskMesg = JsonConvert.DeserializeObject <IndexTask>(message);

                var objType   = taskMesg.type;
                var objCode   = taskMesg.code;
                var cycleType = taskMesg.cycle;// (TechCycle)Enum.Parse(typeof(TechCycle), taskMesg.cycle, true);
                //var date = taskMesg.date;
                IIndexService indexService = new IndexService();
                //获取数据
                var priceList = indexService.GetObjectData(objType.ToString(), cycleType, objCode);

                //计算指数结果
                //存储指数到MangoDB
                //更新状态数据到MangoDB
                if (priceList.Count > 0)
                {
                    var tech = new TechCalculate(objType, cycleType, objCode, priceList);
                    tech.Run();
                }
                this.Log().Info("处理完成");
                _socket.Send("处理完成:{" + message + "}");
            }
        }
コード例 #5
0
        public void Execute(IJobExecutionContext context)
        {
            LoggingExtensions.Logging.Log.InitializeWith <LoggingExtensions.log4net.Log4NetLog>();

            using (NetMQContext nmContext = NetMQContext.Create())
                using (NetMQSocket socket = nmContext.CreateSocket(ZmqSocketType.Rep))
                {
                    socket.Connect("tcp://localhost:5566");
                    while (true)
                    {
                        var message = socket.ReceiveString();

                        var taskMesg = JsonConvert.DeserializeObject <IndexTask>(message);

                        var objType   = taskMesg.type;
                        var objCode   = taskMesg.code;
                        var cycleType = taskMesg.cycle;// (TechCycle)Enum.Parse(typeof(TechCycle), taskMesg.cycle, true);

                        IIndexService indexService = new IndexService();
                        //获取数据
                        var priceList = indexService.GetObjectData(objType.ToString(), cycleType, objCode);

                        //计算指数结果
                        //存储指数到MangoDB
                        //更新状态数据到MangoDB
                        var tech = new TechCalculate(objType, cycleType, objCode, priceList);
                        tech.Run();
                    }
                }
        }
コード例 #6
0
        public AsyncRequestHandlerSocket(NetMQContext context,
                                         string address,
                                         Func <byte[], TRequest> requestUnmarshaller,
                                         Func <TReply, byte[]> replyMarshaller)
        {
            _requestUnmarshaller = requestUnmarshaller;
            _replyMarshaller     = replyMarshaller;
            _context             = context;
            string s        = address.Split(':')[2];
            int    basePort = int.Parse(s);

            _requestSocket = _context.CreateSocket(ZmqSocketType.Pull);
            _requestSocket.Bind(address);
            _replySocket = _context.CreateSocket(ZmqSocketType.Pub);
            _replySocket.Bind(address.Substring(0, address.LastIndexOf(":")) + ":" + (basePort + 1));
            Task.Factory.StartNew(Run, TaskCreationOptions.LongRunning);
        }
コード例 #7
0
        private void init()
        {
            _context = NetMQContext.Create();

            _socket = _context.CreateSocket(ZmqSocketType.Req);

            _socket.Connect("tcp://localhost:5559");
        }
コード例 #8
0
 public RequestSocket(NetMQContext context,
                      string address,
                      Func <TRequest, byte[]> requestMarshaller,
                      Func <byte[], TReply> replyUnmarshaller)
 {
     _requestMarshaller = requestMarshaller;
     _replyUnmarshaller = replyUnmarshaller;
     _socket            = context.CreateSocket(ZmqSocketType.Req);
     _socket.Connect(address);
     _internalChannel.SetRequestHandler(StubFiber.StartNew(), InternalSendRequest);
 }
コード例 #9
0
        public void Start()
        {
            SignalService.Logger.Info("Bind zeroMQ socket to address: {0}", Address);
            router = zeroMQContext.CreateSocket(ZmqSocketType.Router);
            router.Bind(Address);
            router.ReceiveReady += RouterOnReceiveReady;
            //poller = new Poller();
            //poller.AddSocket(router);

            //new Thread(() => poller.Start()).Start(); // TODO stop thread
            new Thread(PollerThread).Start();
        }
コード例 #10
0
 public RequestHandlerSocket(NetMQContext context,
                             string address,
                             Func <byte[], TRequest> requestUnmarshaller,
                             Func <TReply, byte[]> replyMarshaller)
 {
     _requestUnmarshaller = requestUnmarshaller;
     _replyMarshaller     = replyMarshaller;
     _timeout             = TimeSpan.FromMilliseconds(100);
     _socket = context.CreateSocket(ZmqSocketType.Rep);
     _socket.Bind(address);
     Task.Factory.StartNew(Run, TaskCreationOptions.LongRunning);
 }
コード例 #11
0
        public AsyncRequestSocket(NetMQContext context,
                                  string address,
                                  Func <TRequest, byte[]> requestMarshaller,
                                  Func <byte[], TReply> replyUnmarshaller,
                                  IFiber fiber)
        {
            _requestMarshaller = requestMarshaller;
            _replyUnmarshaller = replyUnmarshaller;
            _fiber             = fiber;
            _internalChannel.SetRequestHandler(_fiber, OnRequest);
            _replyContext = context;
            int basePort = int.Parse(address.Split(':')[2]);

            _replySocket = _replyContext.CreateSocket(ZmqSocketType.Sub);
            _replySocket.Connect(address.Substring(0, address.LastIndexOf(":")) + ":" + (basePort + 1));
            _replySocket.Subscribe(_id);
            _requestSocket = _replyContext.CreateSocket(ZmqSocketType.Push);
            _requestSocket.Connect(address);
            _fiber.Start();
            Task.Factory.StartNew(Run, TaskCreationOptions.LongRunning);
        }
コード例 #12
0
ファイル: PullSocket.cs プロジェクト: JackWangCUMT/Fibrous
 public PullSocket(NetMQContext context, string address, Func <byte[], T> msgReceiver, IPublisherPort <T> output, bool useBind = true)
     : base(context, msgReceiver, output)
 {
     Socket = context.CreateSocket(ZmqSocketType.Pull);
     if (useBind)
     {
         Socket.Bind(address);
     }
     else
     {
         Socket.Connect(address);
     }
     Initialize();
 }
コード例 #13
0
        /// <summary>
        /// Starts the server.
        /// </summary>
        public void StartServer()
        {
            if (_runServer)
            {
                return;
            }

            _runServer = true;
            _context   = NetMQContext.Create();

            _socket = _context.CreateSocket(NetMQ.zmq.ZmqSocketType.Rep);
            _socket.Bind("tcp://*:" + _socketPort);
            _socket.ReceiveReady += _socket_ReceiveReady;
            _poller = new Poller(new[] { _socket });

            Task.Factory.StartNew(_poller.Start, TaskCreationOptions.LongRunning);
        }
コード例 #14
0
 //? swtich to ctor with Socket and Sender?  move setup to factory?
 public SendSocket(NetMQContext context,
                   string address,
                   Func <T, byte[]> marshaller,
                   ZmqSocketType type = ZmqSocketType.Pub,
                   bool bind          = true)
 {
     _msgSender = marshaller;
     _socket    = context.CreateSocket(type);
     if (bind)
     {
         _socket.Bind(address);
     }
     else
     {
         _socket.Connect(address);
     }
 }
コード例 #15
0
 private void InitLinks(NetMQContext ctx, ConcurrentDictionary <string, Link> links, QueueLinks queue, ZmqSocketType socketType)
 {
     foreach (LinkAddress sa in queue.Links)
     {
         log.InfoFormat("Connecting to {0}({1})", sa.Name, sa.Address);
         Link link = new Link
         {
             service = sa.Name,
             address = sa.Address,
             context = ctx,
             socket  = ctx.CreateSocket(socketType),
         };
         link.socket.Options.Identity = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString());
         link.Connect();
         links[sa.Name] = link;
     }
 }
コード例 #16
0
        /// <summary>
        /// Start the server.
        /// </summary>
        public void StartServer()
        {
            //check that it's not already running
            if (ServerRunning)
            {
                return;
            }
            _context = NetMQContext.Create();

            _routerSocket = _context.CreateSocket(NetMQ.zmq.ZmqSocketType.Router);
            _routerSocket.Bind("tcp://*:" + _listenPort);
            _routerSocket.ReceiveReady += socket_ReceiveReady;

            _poller = new Poller(new[] { _routerSocket });

            Task.Factory.StartNew(_poller.Start, TaskCreationOptions.LongRunning);

            ServerRunning = true;
        }
コード例 #17
0
        /// <summary>
        /// Starts the publishing and request servers.
        /// </summary>
        public void StartServer()
        {
            if (!ServerRunning)
            {
                _context = NetMQContext.Create();

                //the publisher socket
                _pubSocket = _context.CreatePublisherSocket();
                _pubSocket.Bind("tcp://*:" + PublisherPort);

                //the request socket
                _reqSocket = _context.CreateSocket(ZmqSocketType.Rep);
                _reqSocket.Bind("tcp://*:" + RequestPort);
                _reqSocket.ReceiveReady += _reqSocket_ReceiveReady;

                _poller = new Poller(new[] { _reqSocket });
                Task.Factory.StartNew(_poller.Start, TaskCreationOptions.LongRunning);
            }
            ServerRunning = true;
        }
コード例 #18
0
        /// <summary>
        /// Tries to connect to the QDMS server.
        /// </summary>
        public void Connect()
        {
            Dispose();

            _context      = NetMQContext.Create();
            _reqSocket    = _context.CreateDealerSocket();
            _subSocket    = _context.CreateSubscriberSocket();
            _dealerSocket = _context.CreateSocket(ZmqSocketType.Dealer);

            _reqSocket.Options.Identity    = Encoding.UTF8.GetBytes(_name);
            _subSocket.Options.Identity    = Encoding.UTF8.GetBytes(_name);
            _dealerSocket.Options.Identity = Encoding.UTF8.GetBytes(_name);

            _dealerSocket.ReceiveReady += _dealerSocket_ReceiveReady;
            _reqSocket.ReceiveReady    += _reqSocket_ReceiveReady;
            _subSocket.ReceiveReady    += _subSocket_ReceiveReady;

            _reqSocket.Connect(string.Format("tcp://{0}:{1}", _host, _realTimeRequestPort));

            //start off by sending a ping to make sure everything is regular
            string reply = "";

            try
            {
                _reqSocket.SendMore("");
                _reqSocket.Send("PING");

                _reqSocket.ReceiveString(TimeSpan.FromSeconds(1)); //empty frame starts the REP message //todo receive string?
                reply = _reqSocket.ReceiveString(TimeSpan.FromMilliseconds(50));
            }
            catch
            {
                Dispose();
            }


            if (reply != "PONG") //server didn't reply or replied incorrectly
            {
                _reqSocket.Disconnect(string.Format("tcp://{0}:{1}", _host, _realTimeRequestPort));
                _reqSocket.Close();
                {
                    RaiseEvent(Error, this, new ErrorArgs(-1, "Could not connect to server."));
                    return;
                }
            }

            _lastHeartBeat = DateTime.Now;
            _subSocket.Connect(string.Format("tcp://{0}:{1}", _host, _realTimePublishPort));
            _dealerSocket.Connect(string.Format("tcp://{0}:{1}", _host, _historicalDataPort));

            _running = true;

            //this loop sends out historical data requests and receives the data
            _dealerLoopThread = new Thread(DealerLoop)
            {
                Name = "Client Dealer Loop"
            };
            _dealerLoopThread.Start();

            //this loop takes care of replies to the request socket: heartbeats and data request status messages
            _poller = new Poller();
            _poller.AddSocket(_reqSocket);
            _poller.AddSocket(_subSocket);
            _poller.AddSocket(_dealerSocket);
            Task.Factory.StartNew(_poller.Start, TaskCreationOptions.LongRunning);

            _heartBeatTimer          = new Timer(1000);
            _heartBeatTimer.Elapsed += _timer_Elapsed;
            _heartBeatTimer.Start();
        }
コード例 #19
0
        /// <summary>
        /// Query the server for contracts matching a particular set of features.
        /// </summary>
        /// <param name="instrument">An Instrument object; any features that are not null will be search parameters. If null, all instruments are returned.</param>
        /// <returns>A list of instruments matching these features.</returns>
        public List <Instrument> FindInstruments(Instrument instrument = null)
        {
            if (!Connected)
            {
                RaiseEvent(Error, this, new ErrorArgs(-1, "Could not request instruments - not connected."));
                return(new List <Instrument>());
            }

            using (NetMQSocket s = _context.CreateSocket(ZmqSocketType.Req))
            {
                s.Connect(string.Format("tcp://{0}:{1}", _host, _instrumentServerPort));
                var ms = new MemoryStream();

                if (instrument == null) //all contracts
                {
                    s.Send("ALL");
                }
                else //an actual search
                {
                    s.SendMore("SEARCH"); //first we send a search request

                    //then we need to serialize and send the instrument
                    s.Send(MyUtils.ProtoBufSerialize(instrument, ms));
                }

                //first we receive the size of the final uncompressed byte[] array
                bool   hasMore;
                byte[] sizeBuffer = s.Receive(out hasMore);
                if (sizeBuffer.Length == 0)
                {
                    RaiseEvent(Error, this, new ErrorArgs(-1, "Contract request failed, received no reply."));
                    return(new List <Instrument>());
                }

                int outputSize = BitConverter.ToInt32(sizeBuffer, 0);

                //then the actual data
                byte[] buffer = s.Receive(out hasMore);
                if (buffer.Length == 0)
                {
                    RaiseEvent(Error, this, new ErrorArgs(-1, "Contract request failed, received no data."));
                    return(new List <Instrument>());
                }

                try
                {
                    //then we process it by first decompressing
                    ms.SetLength(0);
                    byte[] decoded = LZ4Codec.Decode(buffer, 0, buffer.Length, outputSize);
                    ms.Write(decoded, 0, decoded.Length);
                    ms.Position = 0;

                    //and finally deserializing
                    return(Serializer.Deserialize <List <Instrument> >(ms));
                }
                catch (Exception ex)
                {
                    RaiseEvent(Error, this, new ErrorArgs(-1, "Error processing instrument data: " + ex.Message));
                    return(new List <Instrument>());
                }
            }
        }