Exemplo n.º 1
0
        public static void TIClient(string[] args)
        {
            bool verbose = (args.Any(e => e.ToLower().Equals("-v")
                                          || e.ToLower().Equals("--verbose")));
            Console.WriteLine("Verbose: {0}", verbose);

            CancellationTokenSource cancellor = new CancellationTokenSource();
            Console.CancelKeyPress += (s, ea) =>
            {
                ea.Cancel = true;
                cancellor.Cancel();
            };

            using (MajordomoClient session = new MajordomoClient("tcp://localhost:5555", verbose))
            {
                //  1. Send 'echo' request to Titanic
                ZMessage request = new ZMessage();
                request.Add(new ZFrame("echo"));
                request.Add(new ZFrame("Hello World"));

                Guid uuid = Guid.Empty;
                using (var reply = TIClient_ServiceCall(session, "titanic.request", request, cancellor))
                {
                    if (reply != null)
                    {
                        uuid = Guid.Parse(reply.PopString());
                        "I: request UUID {0}".DumpString(uuid);
                    }
                }

                // 2. Wait until we get a reply
                while (!cancellor.IsCancellationRequested)
                {
                    Thread.Sleep(100);
                    request.Dispose();
                    request = new ZMessage();
                    request.Add(new ZFrame(uuid.ToString()));
                    var reply = TIClient_ServiceCall(session, "titanic.reply", request, cancellor);
                    if (reply != null)
                    {
                        string replystring = reply.Last().ToString();
                        "Reply: {0}\n".DumpString(replystring);
                        reply.Dispose();

                        // 3. Close Request
                        request.Dispose();
                        request = new ZMessage();
                        request.Add(new ZFrame(uuid.ToString()));
                        reply = TIClient_ServiceCall(session, "titanic.close", request, cancellor);
                        reply.Dispose();
                        break;
                    }
                    else
                    {
                        "I: no reply yet, trying again...\n".DumpString();
                        Thread.Sleep(5000); // try again in 5 seconds
                    }
                }
            }
        }
Exemplo n.º 2
0
        public static void PSEnvPub(IDictionary <string, string> dict, string[] args)
        {
            //
            // Pubsub envelope publisher
            //
            // Author: metadings
            //

            // Prepare our context and publisher
            using (var context = new ZContext())
                using (var publisher = new ZSocket(context, ZSocketType.PUB))
                {
                    publisher.Linger = TimeSpan.Zero;
                    publisher.Bind("tcp://*:5563");

                    while (true)
                    {
                        // Write two messages, each with an envelope and content
                        using (var message = new ZMessage())
                        {
                            message.Add(new ZFrame("A"));
                            message.Add(new ZFrame("We don't want to see this"));
                            publisher.Send(message);
                        }
                        using (var message = new ZMessage())
                        {
                            message.Add(new ZFrame("B"));
                            message.Add(new ZFrame("We would like to see this"));
                            publisher.Send(message);
                        }
                        Thread.Sleep(1000);
                    }
                }
        }
Exemplo n.º 3
0
        public static void PSEnvPub(IDictionary <string, string> dict, string[] args)
        {
            //
            // Pubsub envelope publisher
            //
            // Authors: Pieter Hintjens, Uli Riehm
            //

            // Prepare our context and publisher
            using (var context = ZContext.Create())
                using (var publisher = ZSocket.Create(context, ZSocketType.PUB))
                {
                    publisher.Bind("tcp://*:5563");

                    while (true)
                    {
                        // Write two messages, each with an envelope and content
                        using (var message = new ZMessage())
                        {
                            message.Add(new ZFrame("A"));
                            message.Add(new ZFrame("We don't want to see this"));
                            publisher.Send(message);
                        }
                        using (var message = new ZMessage())
                        {
                            message.Add(new ZFrame("B"));
                            message.Add(new ZFrame("We would like to see this"));
                            publisher.Send(message);
                        }
                        Thread.Sleep(1);
                    }
                }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Sends data to the server asynchronously.
        /// </summary>
        /// <param name="data">The buffer that contains the binary data to be sent.</param>
        /// <param name="offset">The zero-based position in the <paramref name="data"/> at which to begin sending data.</param>
        /// <param name="length">The number of bytes to be sent from <paramref name="data"/> starting at the <paramref name="offset"/>.</param>
        /// <returns><see cref="WaitHandle"/> for the asynchronous operation.</returns>
        protected override WaitHandle SendDataAsync(byte[] data, int offset, int length)
        {
            if (CurrentState != ClientState.Connected)
            {
                throw new SocketException((int)SocketError.NotConnected);
            }

            try
            {
                if ((object)m_zeroMQClient.Provider != null)
                {
                    using (ZMessage message = new ZMessage())
                    {
                        // Dealer socket will auto-add identity, just add delimiter and data payload frames
                        message.Add(new ZFrame());
                        message.Add(new ZFrame(data, offset, length));

                        // ZeroMQ send is asynchronous, but API call is not thread-safe
                        lock (m_sendLock)
                            m_zeroMQClient.Provider.Send(message);
                    }

                    m_zeroMQClient.Statistics.UpdateBytesSent(length);
                }
            }
            catch (Exception ex)
            {
                // Log exception during send operation
                OnSendDataException(ex);
            }

            return(m_completedHandle.WaitHandle);
        }
Exemplo n.º 5
0
        private static void Publisher(ZContext context)
        {
            using (var publisher = new ZSocket(context, ZSocketType.PUB))
            {
                publisher.Bind(endpointUrlPublisher);

                while (isRunning && !cts.IsCancellationRequested)
                {
                    object currentMessage;
                    if (outbox.TryDequeue(out currentMessage))
                    {
                        using (var message = new ZMessage())
                        {
                            try
                            {
                                var json = JsonConvert.SerializeObject(currentMessage);
                                message.Add(new ZFrame("info"));
                                message.Add(new ZFrame(json));
                                publisher.Send(message);
                            }
                            catch (Exception ex)
                            {
                                //TODO: Add logging
                            }
                        }
                    }
                    else
                    {
                        Thread.Sleep(10);
                    }
                }
                isRunning = false;
            }
        }
Exemplo n.º 6
0
        public static void Send(string identity, string message)
        {
            lock (_workerThreads)
            {
                // Find last worker socket this client was connected to (should still be connected)
                var workerThread = _workerThreads.FirstOrDefault(x => x.LastConnectedClientIdentity == identity);
                if (workerThread != null && workerThread.Thread != null && workerThread.Socket != null)
                {
                    using (var response = new ZMessage())
                    {
                        response.Add(new ZFrame(identity));
                        response.Add(new ZFrame(message));

                        ZError error;
                        if (!workerThread.Socket.Send(response, out error))
                        {
                            if (error == ZError.ETERM)
                            {
                                return; // Interrupted
                            }
                            throw new ZException(error);
                        }
                    }
                }
            }
        }
Exemplo n.º 7
0
        public void Start()
        {
            _serverToWorkerSocket = new ZSocket(_context, ZSocketType.DEALER);
            _serverToWorkerSocket.Connect("inproc://server-to-workers");

            _serverToWorkerSocket = new ZSocket(_context, ZSocketType.ROUTER);
            _serverToWorkerSocket.Connect("inproc://workers-to-server");

            WriteLine("Started...");

            ZMessage request;

            while (true)
            {
                if (null == (request = _serverToWorkerSocket.ReceiveMessage(out ZError error)))
                {
                    Stop(error);
                }
                using (request)
                {
                    var identity = request[0].ReadString();
                    var msg      = request[1].ReadString();

                    WriteLine($"Received from {identity}: {msg}. Distributing...");

                    using (var message = new ZMessage())
                    {
                        message.Add(new ZFrame(identity));
                        message.Add(new ZFrame(msg));

                        _serverToWorkerSocket.Send(message);
                    }
                }
            }
        }
Exemplo n.º 8
0
        /// <summary>
        ///     一次请求
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="desicription"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static ZeroResultData QuietSend(this ZSocket socket, byte[] desicription, params string[] args)
        {
            var message = new ZMessage();
            var frame   = new ZFrame(desicription);

            message.Add(frame);
            if (args != null)
            {
                foreach (var arg in args)
                {
                    message.Add(new ZFrame(arg.ToZeroBytes()));
                }
            }
            if (!socket.SendTo(message))
            {
                return(new ZeroResultData
                {
                    State = ZeroOperatorStateType.LocalRecvError,
                    ZmqError = socket.LastError
                });
            }
            return(new ZeroResultData
            {
                State = ZeroOperatorStateType.Ok,
                InteractiveSuccess = true
            });
        }
Exemplo n.º 9
0
        public static void Main(string[] args)
        {
            using (var context = new ZContext())
                using (var publisher = new ZSocket(context, ZSocketType.PUB))
                {
                    //publisher.Linger = TimeSpan.Zero;
                    publisher.Bind("tcp://*:5555");

                    int published = 0;
                    while (true)
                    {
                        using (var message = new ZMessage())
                        {
                            published++;
                            message.Add(new ZFrame(string.Format("B {0}", published)));
                            message.Add(new ZFrame(string.Format("Still to New Year {0} days", (new DateTime(DateTime.Now.Year + 1, 01, 01) - DateTime.Now).Days.ToString())));
                            Thread.Sleep(10000);

                            Console.WriteLine("Publishing" + " the message is sent");
                            publisher.Send(message);
                        }

                        using (var message = new ZMessage())
                        {
                            published++;
                            message.Add(new ZFrame(string.Format("A {0}", published)));
                            message.Add(new ZFrame(string.Format("Heppy New Year!!!")));
                            Thread.Sleep(10000);

                            Console.WriteLine("Publishing " + "the message is sent");
                            publisher.Send(message);
                        }
                    }
                }
        }
Exemplo n.º 10
0
        private void RelayMinerInfo(MinerInfo minerInfo)
        {
            try
            {
                var flags = (int)RelayInfo.WireFormat.ProtocolBuffers;

                using (var msg = new ZMessage())
                {
                    // Topic frame
                    msg.Add(new ZFrame(minerInfo.PoolId));

                    // Frame 2: flags
                    msg.Add(new ZFrame(flags));

                    // Frame 3: content type
                    msg.Add(new ZFrame(RelayContentType.MinerInfo.ToString()));

                    // Frame 4: payload
                    using (var stream = new MemoryStream())
                    {
                        Serializer.Serialize(stream, minerInfo);
                        msg.Add(new ZFrame(stream.ToArray()));
                    }

                    pubSocket.SendMessage(msg);
                }
            }

            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
Exemplo n.º 11
0
        public static void PSEnvPub(string[] args)
        {
            //
            // Pubsub envelope publisher
            //
            // Author: metadings
            //

            // Prepare our context and publisher
            using (var context = new ZContext())
            using (var publisher = new ZSocket(context, ZSocketType.PUB))
            {
                publisher.Linger = TimeSpan.Zero;
                publisher.Bind("tcp://*:5563");

                while (true)
                {
                    // Write two messages, each with an envelope and content
                    using (var message = new ZMessage())
                    {
                        message.Add(new ZFrame("A"));
                        message.Add(new ZFrame("We don't want to see this"));
                        publisher.Send(message);
                    }
                    using (var message = new ZMessage())
                    {
                        message.Add(new ZFrame("B"));
                        message.Add(new ZFrame("We would like to see this"));
                        publisher.Send(message);
                    }
                    Thread.Sleep(1000);
                }
            }
        }
Exemplo n.º 12
0
 private void Login(ZMessage zMsgReply, string traderName, string psw)
 {
     if (DictUserLogin.ContainsKey(traderName))
     {
         if (Program.db.平台用户.ExistsUser(traderName, psw))
         {
             DictUserLogin[traderName] = DateTime.Now;
             FectchAllTable(traderName);
             zMsgReply.Add(new ZFrame(string.Format("0|{0}|{1}|{2}|登录更新成功", traderName, 1, string.Empty)));
         }
         else
         {
             zMsgReply.Add(new ZFrame(string.Format("0|{0}|{1}|{2}|登录更新失败,用户名或密码错误", traderName, 0, string.Empty)));
         }
     }
     else if (Program.db.平台用户.ExistsUser(traderName, psw))
     {
         if (!DictUserLogin.TryAdd(traderName, DateTime.Now))
         {
             DictUserLogin[traderName] = DateTime.Now;
         }
         FectchAllTable(traderName);
         zMsgReply.Add(new ZFrame(string.Format("0|{0}|{1}|{2}|登录成功", traderName, 1, string.Empty)));
     }
     else
     {
         zMsgReply.Add(new ZFrame(string.Format("0|{0}|{1}|{2}|登录失败,用户名或密码错误", traderName, 0, string.Empty)));
     }
 }
Exemplo n.º 13
0
        public static void SendSignal(String adr)
        {
            ZContext context = Context.GetContext();

            using (var client = new ZSocket(context, ZSocketType.DEALER))
            {
                client.Connect(adr);
                ZError error;

                using (var outgoing = new ZMessage())
                {
                    outgoing.Add(new ZFrame(adr));
                    outgoing.Add(new ZFrame("wakeup"));

                    if (!client.Send(outgoing, out error))
                    {
                        Console.WriteLine("error");
                        if (error == ZError.ETERM)
                        {
                            return;    // Interrupted
                        }
                        throw new ZException(error);
                    }
                    Console.WriteLine("send wakeup to {0}", adr);
                }
            }
        }
        public void SendMessage(String messageId, MessageType messageType, String message, String replyTo = null)
        {
            ZError error;
            String id = messageId;

            if (String.IsNullOrWhiteSpace(id))
            {
                id = Guid.NewGuid().ToString();
            }
            using (ZMessage outgoing = new ZMessage())
            {
                if (replyTo == null)
                {
                    outgoing.Add(new ZFrame(Socket.Identity));
                }
                else
                {
                    outgoing.Add(new ZFrame(Encoding.UTF8.GetBytes(replyTo)));
                }
                outgoing.Add(new ZFrame(id));
                outgoing.Add(new ZFrame(messageType.ToString()));
                outgoing.Add(new ZFrame(message));
                Console.WriteLine("<<< [" + id + "][" + messageType + "] " + message);
                if (!Socket.Send(outgoing, out error))
                {
                    if (error == ZError.ETERM)
                    {
                        return;
                    }
                    throw new ZException(error);
                }
            }
        }
Exemplo n.º 15
0
        public void StartRouterServer(string endpoint)
        {
            Endpoint = endpoint;
            using (var router = new ZSocket(ChatNodeV2.Context, ZSocketType.ROUTER))
            {
                router.Bind(Endpoint);
                activeSocket = router;
                ZError   error;
                ZMessage request;

                while (true)
                {
                    if (null == (request = router.ReceiveMessage(out error)))
                    {
                        if (error == ZError.ETERM)
                        {
                            return;    // Interrupted
                        }
                        throw new ZException(error);
                    }
                    IsStarted = true;
                    using (request)
                    {
                        // The DEALER socket gives us the reply envelope and message
                        string identity = request[1].ReadString();
                        string content  = request[2].ReadString();

                        using (var received = new ZMessage())
                        {
                            received.Add(new ZFrame(identity));
                            received.Add(new ZFrame($"Server respose to [{content}] @ [{DateTime.Now.ToLongTimeString()}]"));

                            router.SendMore(received[0]);
                            router.SendMore(new ZFrame());
                            router.SendMore(received[1]);

                            List <ZFrame> primljenePoruke = new List <ZFrame>();
                            primljenePoruke.AddRange(received);
                            _receiveList.AddRange(primljenePoruke);

                            foreach (ZFrame item in _receiveList)
                            {
                                _output.Add(item);
                            }
                            _receiveList.Clear();

                            if (!router.Send(received, out error))
                            {
                                if (error == ZError.ETERM)
                                {
                                    return;    // Interrupted
                                }
                                throw new ZException(error);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 16
0
        static void LBBroker_Worker(ZContext context, int i)
        {
            // This is the worker task, using a REQ socket to do load-balancing.

            // Create socket
            using (var worker = new ZSocket(context, ZSocketType.REQ))
            {
                // Set a printable identity
                worker.IdentityString = "WORKER" + i;

                // Connect
                worker.Connect("inproc://backend");

                // Tell broker we're ready for work
                using (var ready = new ZFrame("READY"))
                {
                    worker.Send(ready);
                }

                ZError   error;
                ZMessage request;

                while (true)
                {
                    // Get request
                    if (null == (request = worker.ReceiveMessage(out error)))
                    {
                        // We are using "out error",
                        // to NOT throw a ZException ETERM
                        if (error == ZError.ETERM)
                        {
                            break;
                        }

                        throw new ZException(error);
                    }

                    using (request)
                    {
                        request.DumpZmsg("---worker received from broker---");
                        string client_id   = request[0].ReadString();
                        string requestText = request[2].ReadString();

                        Console.WriteLine("WORKER{0}: {1}", i, requestText);

                        // Send reply
                        using (var commit = new ZMessage())
                        {
                            commit.Add(new ZFrame(client_id));
                            commit.Add(new ZFrame());
                            commit.Add(new ZFrame("OK"));

                            worker.Send(commit);
                        }
                    }
                }
            }
        }
Exemplo n.º 17
0
        public static void TIClient(string[] args)
        {
            CancellationTokenSource cancellor = new CancellationTokenSource();

            Console.CancelKeyPress += (s, ea) =>
            {
                ea.Cancel = true;
                cancellor.Cancel();
            };

            using (MajordomoClient session = new MajordomoClient("tcp://127.0.0.1:5555", Verbose))
            {
                //  1. Send 'echo' request to Titanic
                ZMessage request = new ZMessage();
                request.Add(new ZFrame("echo"));
                request.Add(new ZFrame("Hello World"));

                Guid uuid = Guid.Empty;
                using (var reply = TIClient_ServiceCall(session, "titanic.request", request, cancellor))
                {
                    if (reply != null)
                    {
                        uuid = Guid.Parse(reply.PopString());
                        "I: request UUID {0}".DumpString(uuid);
                    }
                }

                // 2. Wait until we get a reply
                while (!cancellor.IsCancellationRequested)
                {
                    Thread.Sleep(100);
                    request.Dispose();
                    request = new ZMessage();
                    request.Add(new ZFrame(uuid.ToString()));
                    var reply = TIClient_ServiceCall(session, "titanic.reply", request, cancellor);
                    if (reply != null)
                    {
                        string replystring = reply.Last().ToString();
                        "Reply: {0}\n".DumpString(replystring);
                        reply.Dispose();

                        // 3. Close Request
                        request.Dispose();
                        request = new ZMessage();
                        request.Add(new ZFrame(uuid.ToString()));
                        reply = TIClient_ServiceCall(session, "titanic.close", request, cancellor);
                        reply.Dispose();
                        break;
                    }
                    else
                    {
                        "I: no reply yet, trying again...\n".DumpString();
                        Thread.Sleep(5000);                         // try again in 5 seconds
                    }
                }
            }
        }
Exemplo n.º 18
0
        //public override void SendMore(byte[] envelope)
        //{
        //    this.innerSocket.SendMore(envelope);
        //}

        //public override void Send(byte[] data)
        //{
        //    this.innerSocket.Send(data);
        //}

        //public override byte[] Receive()
        //{
        //    return this.innerSocket.Receive();
        //}

        public override void Send(byte[] envelope, byte[] data)
        {
            using (var message = new ZMessage())
            {
                message.Add(new ZFrame(envelope));
                message.Add(new ZFrame(data));
                this.innerSocket.Send(message);
            }
        }
Exemplo n.º 19
0
 private void SendEvent(String msg)
 {
     using (ZMessage message = new ZMessage())
     {
         message.Add(new ZFrame("event"));
         message.Add(new ZFrame(msg));
         publisher.Send(message);
     }
 }
Exemplo n.º 20
0
        /// <summary>
        /// not threadsave! 1 socket created by constructor
        /// http://zguide.zeromq.org/page:all
        /// - Do not try to use the same socket from multiple threads.
        /// </summary>
        /// <param name="wsCtx"></param>
        public void Send(WorkloadStatisticsContext wsCtx)
        {
            var msg = new ZMessage();

            msg.Add(new ZFrame(wsCtx.GroupGuid.ToString()));
            msg.Add(new ZFrame(wsCtx.TaskGuid.ToString()));
            msg.Add(new ZFrame(wsCtx.ToString()));
            _pubSocket.Send(msg);
        }
Exemplo n.º 21
0
 private void Send(string value)
 {
     using (var message = new ZMessage())
     {
         message.Add(new ZFrame(MessageName));
         message.Add(new ZFrame(value));
         publisher.Send(message);
     }
 }
Exemplo n.º 22
0
        public static void SendRcvMsg(String identity, String text, String adr1, String adr2)
        {
            ZContext context = Context.GetContext();

            using (var client = new ZSocket(context, ZSocketType.DEALER))
            {
                client.Identity = Encoding.UTF8.GetBytes(identity);
                client.Connect(adr2);

                ZError error;
                //ZMessage incoming;
                //var poll = ZPollItem.CreateReceiver();

                using (var outgoing = new ZMessage())
                {
                    outgoing.Add(new ZFrame(client.Identity));
                    outgoing.Add(new ZFrame(adr1));
                    outgoing.Add(new ZFrame(text));

                    if (!client.Send(outgoing, out error))
                    {
                        Console.WriteLine("error");
                        if (error == ZError.ETERM)
                        {
                            return;    // Interrupted
                        }
                        throw new ZException(error);
                    }

                    Console.WriteLine("{0} send: {1}", identity, text);
                }

                /*while (true)
                 * {
                 *  if (!client.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(10)))
                 *  {
                 *      Console.WriteLine("error: reader/writer while receiving");
                 *
                 *      if (error == ZError.EAGAIN)
                 *      {
                 *          Thread.Sleep(1);
                 *          continue;
                 *      }
                 *      if (error == ZError.ETERM)
                 *          return;    // Interrupted
                 *      throw new ZException(error);
                 *  }
                 *
                 *  using (incoming)
                 *  {
                 *      string messageText = incoming[1].ReadString();
                 *      Console.WriteLine("{0} received: {1}", identity, messageText);
                 *  }
                 * }*/
            }
        }
Exemplo n.º 23
0
 public void Send(int processId, string body, string routingKey)
 {
     using (var message = new ZMessage())     //HACK: can we reuse instance between events?
     {
         message.Add(new ZFrame(routingKey)); //envelope name
         message.Add(new ZFrame(processId));  //process id
         message.Add(new ZFrame(body));       //body
         _sock.Send(message);
     }
 }
Exemplo n.º 24
0
        static void AsyncSrv_ServerWorker(ZContext context, int i)
        {
            // Each worker task works on one request at a time and sends a random number
            // of replies back, with random delays between replies:

            using (var worker = ZSocket.Create(context, ZSocketType.DEALER))
            {
                worker.Connect("inproc://backend");

                ZError   error;
                ZMessage request;
                var      rnd = new Random();

                while (true)
                {
                    if (null == (request = worker.ReceiveMessage(out error)))
                    {
                        if (error == ZError.ETERM)
                        {
                            return;                             // Interrupted
                        }
                        throw new ZException(error);
                    }
                    using (request)
                    {
                        // The DEALER socket gives us the reply envelope and message
                        string identity = request[1].ReadString();
                        string content  = request[2].ReadString();

                        // Send 0..4 replies back
                        int replies = rnd.Next(5);
                        for (int reply = 0; reply < replies; ++reply)
                        {
                            // Sleep for some fraction of a second
                            Thread.Sleep(rnd.Next(1000) + 1);

                            using (var response = new ZMessage())
                            {
                                response.Add(new ZFrame(identity));
                                response.Add(new ZFrame(content));

                                if (!worker.Send(response, out error))
                                {
                                    if (error == ZError.ETERM)
                                    {
                                        return;                                         // Interrupted
                                    }
                                    throw new ZException(error);
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Client
        /// </summary>
        /// <param name="context"></param>
        /// <param name="i"></param>
        private static void AsyncSrv_Client(ZContext context, int i)
        {
            using (var client = new ZSocket(context, ZSocketType.DEALER))
            {
                client.Identity = Encoding.UTF8.GetBytes("Client" + i);
                client.Connect("tcp://127.0.0.1:5570");
                var poll     = ZPollItem.CreateReceiver();
                var requests = 0;
                while (true)
                {
                    ZError error;
                    for (var centitick = 0; centitick < 100; ++centitick)
                    {
                        if (!client.PollIn(poll, out var incoming, out error, TimeSpan.FromMilliseconds(10)))
                        {
                            if (Equals(error, ZError.EAGAIN))
                            {
                                Thread.Sleep(1);
                                continue;
                            }
                            if (Equals(error, ZError.ETERM))
                            {
                                continue;                                // Interrupted
                            }
                            throw new ZException(error);
                        }
                        using (incoming)
                        {
                            Console.WriteLine("--------------client-----------------");
                            for (var j = 0; j < incoming.Count; j++)
                            {
                                Console.WriteLine($"    {j}:{incoming[j].ReadString()}");
                            }
                            Console.WriteLine("--------------client-----------------");
                        }
                    }
                    using (var outgoing = new ZMessage())
                    {
                        outgoing.Add(new ZFrame("c-xxx"));
                        outgoing.Add(new ZFrame("request " + (++requests)));

                        if (client.Send(outgoing, out error))
                        {
                            continue;
                        }
                        if (Equals(error, ZError.ETERM))
                        {
                            return;                                // Interrupted
                        }
                        throw new ZException(error);
                    }
                }
            }
        }
Exemplo n.º 26
0
 public void Send(IMessage message, string routingKey)
 {
     using (var zmessage = new ZMessage())            //HACK: can we reuse instance between events?
     {
         zmessage.Add(new ZFrame(routingKey));        //envelope name
         zmessage.Add(new ZFrame(message.ProcessId)); //process id
         zmessage.Add(new ZFrame(message.ToJson()));  //body
         zmessage.Add(new ZFrame(message.ToJson()));  //controls whether this is a string orl
         _sock.Send(zmessage);
     }
 }
Exemplo n.º 27
0
        public void PubMarketTransction(MarketTransaction[] transactions)
        {
            if (transactions != null && _isRunning == true)
            {
                if (_isTransport == true)
                {
                    ZMessage message = new ZMessage();
                    message.Add(new ZFrame("transaction"));
                    using (MemoryStream stream = new MemoryStream())
                    {
                        using (GZipStream gzip = new GZipStream(stream, CompressionMode.Compress))
                        {
                            _fmt.Serialize(gzip, transactions);
                            byte[] tmp = stream.ToArray();
                            message.Add(new ZFrame(tmp));
                        }
                    }
                    _transactionCacheGZip.Enqueue(message);
                }
                else
                {
                    foreach (MarketTransaction mt in transactions)
                    {
                        if (mt.Price <= 0 || mt.Volume <= 0)
                        {
                            continue;
                        }
                        ZMessage message = new ZMessage();

                        using (MemoryStream stream = new MemoryStream())
                        {
                            if (_isCompress == true)
                            {
                                message.Add(new ZFrame(mt.Code + ".gzip"));
                                using (GZipStream gzip = new GZipStream(stream, CompressionMode.Compress))
                                {
                                    _fmt.Serialize(gzip, mt);
                                    byte[] tmp = stream.ToArray();
                                    message.Add(new ZFrame(tmp));
                                }
                            }
                            else
                            {
                                message.Add(new ZFrame(mt.Code + ".raw"));
                                _fmt.Serialize(stream, mt);
                                byte[] tmp = stream.ToArray();
                                message.Add(new ZFrame(tmp));
                            }
                        }
                        _transactionCache.Enqueue(message);
                    }
                }
            }
        }
Exemplo n.º 28
0
        public void SendAudio(ZMessage message)
        {
            var response = new ZMessage();

            response.Add(new ZFrame(message[0].ToString() == "Master Unit" ? "Master Unit2" : "Master Unit"));
            for (int i = 1; i < message.Count; i++)
            {
                response.Add(message[i].Duplicate());
            }

            MsgQueue.Enqueue(response);
        }
Exemplo n.º 29
0
        private static void LimitQueryMessageInit(ZMessage zMsgReply, string traderName, ShareLimitGroupItem shareLimitGroup)
        {
            var dict = new Dictionary <string, decimal>();

            if (shareLimitGroup == null)
            {
                Program.logger.LogInfoDetail("{0}额度共享组为空,将返回额度分配表对应配置。", traderName);
                Program.db.额度分配.Where(_ => _.交易员 == traderName).ToList().ForEach(_ => dict.Add(_.证券代码, _.交易额度));
                zMsgReply.Add(new ZFrame(string.Format("5|{0}|{1}", traderName, dict.ToJson())));
            }
            else
            {
                foreach (var item in shareLimitGroup.GroupStockList)
                {
                    var           limit = decimal.Parse(item.LimitCount);
                    decimal       buyCount, saleCount;
                    List <string> lstOrderID = new List <string>();

                    var dictStockBuySaleList = shareLimitGroup.GetShareGroupBuySaleList(item.StockID);
                    shareLimitGroup.GetShareGroupHasBuyCount(item.StockID, out buyCount, out saleCount);

                    decimal needPlaceBuyCount  = 0;
                    decimal needPlaceSaleCount = 0;
                    foreach (var TraderBuySaleItem in dictStockBuySaleList)
                    {
                        if (TraderBuySaleItem.Key != traderName)
                        {
                            if (TraderBuySaleItem.Value.SoldCount > TraderBuySaleItem.Value.BuyCount)
                            {
                                needPlaceBuyCount += TraderBuySaleItem.Value.SoldCount - TraderBuySaleItem.Value.BuyCount;
                            }
                            else
                            {
                                needPlaceSaleCount += TraderBuySaleItem.Value.BuyCount - TraderBuySaleItem.Value.SoldCount;
                            }
                        }
                    }
                    if (dict.ContainsKey(item.StockID))
                    {
                        Program.logger.LogInfoDetail("已存在股票{0}的配置项,股票代码重复", item.StockID);
                    }
                    else
                    {
                        dict.Add(item.StockID, Math.Min(limit - buyCount - needPlaceBuyCount, limit - saleCount - needPlaceSaleCount));
                    }
                }
            }


            zMsgReply.Add(new ZFrame(string.Format("5|{0}|{1}", traderName, dict.ToJson())));
        }
Exemplo n.º 30
0
        public void PubSend(ZSocket publisher, String[] data)
        {
            ZMessage message = new ZMessage();

            message.Add(new ZFrame("A"));
            message.Add(new ZFrame(Methods.LocalIPAddress().ToString()));
            foreach (var item in data)
            {
                message.Add(new ZFrame(item));
            }
            //Console.WriteLine("Publishing ", message);
            PrintMessage("LocalHost", message);
            publisher.Send(message);
        }
Exemplo n.º 31
0
 public void PubMarketData(MarketData[] datas)
 {
     if (datas != null && _isRunning == true)
     {
         if (_isTransport == true)
         {
             ZMessage messageGZip = new ZMessage();
             messageGZip.Add(new ZFrame("data"));
             using (MemoryStream stream = new MemoryStream())
             {
                 using (GZipStream gzip = new GZipStream(stream, CompressionMode.Compress))
                 {
                     _fmt.Serialize(gzip, datas);
                     byte[] tmp = stream.ToArray();
                     messageGZip.Add(new ZFrame(tmp));
                 }
             }
             _dataCacheGZip.Enqueue(messageGZip);
         }
         else
         {
             foreach (MarketData md in datas)
             {
                 ZMessage message = new ZMessage();
                 using (MemoryStream stream = new MemoryStream())
                 {
                     if (_isCompress == true)
                     {
                         message.Add(new ZFrame(md.Code + ".gzip"));
                         using (GZipStream gzip = new GZipStream(stream, CompressionMode.Compress))
                         {
                             _fmt.Serialize(gzip, md);
                             byte[] tmp = stream.ToArray();
                             message.Add(new ZFrame(tmp));
                         }
                     }
                     else
                     {
                         message.Add(new ZFrame(md.Code + ".raw"));
                         _fmt.Serialize(stream, md);
                         byte[] tmp = stream.ToArray();
                         //var tmp = md.ToJSON();
                         message.Add(new ZFrame(tmp));
                     }
                 }
                 _dataCache.Enqueue(message);
             }
         }
     }
 }
Exemplo n.º 32
0
 private void PubMarketOrderQueue(MarketOrderQueue[] orderQueues)
 {
     if (orderQueues != null && _isRunning == true)
     {
         if (_isTransport == true)
         {
             ZMessage message = new ZMessage();
             message.Add(new ZFrame("orderqueue"));
             using (MemoryStream stream = new MemoryStream())
             {
                 using (GZipStream gzip = new GZipStream(stream, CompressionMode.Compress))
                 {
                     _fmt.Serialize(gzip, orderQueues);
                     byte[] tmp = stream.ToArray();
                     message.Add(new ZFrame(tmp));
                 }
             }
             _orderCacheGZip.Enqueue(message);
         }
         else
         {
             foreach (MarketOrderQueue moq in orderQueues)
             {
                 ZMessage message = new ZMessage();
                 using (MemoryStream stream = new MemoryStream())
                 {
                     if (_isCompress == true)
                     {
                         message.Add(new ZFrame(moq.Code + ".gzip"));
                         using (GZipStream gzip = new GZipStream(stream, CompressionMode.Compress))
                         {
                             _fmt.Serialize(gzip, moq);
                             byte[] tmp = stream.ToArray();
                             message.Add(new ZFrame(tmp));
                         }
                     }
                     else
                     {
                         message.Add(new ZFrame(moq.Code + ".raw"));
                         _fmt.Serialize(stream, moq);
                         byte[] tmp = stream.ToArray();
                         message.Add(new ZFrame(tmp));
                     }
                 }
                 _orderQueueCache.Enqueue(message);
             }
         }
     }
 }
Exemplo n.º 33
0
        //  MMI echo query example
        public static void MMIEcho(string[] args)
        {
            bool verbose = (args.Any(e => e.ToLower().Equals("-v")
                                          || e.ToLower().Equals("--verbose")));
            Console.WriteLine("Verbose: {0}", verbose);

            CancellationTokenSource cancellor = new CancellationTokenSource();
            Console.CancelKeyPress += (s, ea) =>
            {
                ea.Cancel = true;
                cancellor.Cancel();
            };

            using (MajordomoClient session = new MajordomoClient("tcp://localhost:5555", verbose))
            {
                ZMessage request  = new ZMessage();
                request.Add(new ZFrame("echo"));

                ZMessage reply = session.Send("mmi.service", request, cancellor);
                if (reply != null)
                {
                    var replycode = reply[0].ToString();
                    "Loopup echo service: {0}\n".DumpString(replycode);
                    reply.Dispose();
                }
                else
                    "E: no response from broker, make sure it's running\n".DumpString();
            }
        }
Exemplo n.º 34
0
        //  MMI echo query example
        public static void MMIEcho(string[] args)
        {
            CancellationTokenSource cancellor = new CancellationTokenSource();
            Console.CancelKeyPress += (s, ea) =>
            {
                ea.Cancel = true;
                cancellor.Cancel();
            };

            using (MajordomoClient session = new MajordomoClient("tcp://127.0.0.1:5555", Verbose))
            {
                ZMessage request  = new ZMessage();
                request.Add(new ZFrame("echo"));

                ZMessage reply = session.Send("mmi.service", request, cancellor);
                if (reply != null)
                {
                    var replycode = reply[0].ToString();
                    "Loopup echo service: {0}\n".DumpString(replycode);
                    reply.Dispose();
                }
                else
                    "E: no response from broker, make sure it's running\n".DumpString();
            }
        }
Exemplo n.º 35
0
		// Basic request-reply client using REQ socket
		static void LBBroker_Client(ZContext context, int i)
		{
			// Create a socket
			using (var client = new ZSocket(context, ZSocketType.REQ))
			{
				// Set a printable identity
				client.IdentityString = "CLIENT" + i;

				// Connect
				client.Connect("inproc://frontend");

				using (var request = new ZMessage())
				{
					request.Add(new ZFrame("Hello"));

					// Send request
					client.Send(request);
				}

				// Receive reply
				using (ZMessage reply = client.ReceiveMessage())
				{
					Console.WriteLine("CLIENT{0}: {1}", i, reply[0].ReadString());
				}
			}
		}
Exemplo n.º 36
0
		public static void PSEnvPub(string[] args)
		{
			//
			// Pubsub envelope publisher
			//
			// Author: metadings
			//

			// Prepare our context and publisher
			using (var context = new ZContext())
			using (var publisher = new ZSocket(context, ZSocketType.PUB))
			{
				publisher.Linger = TimeSpan.Zero;
				publisher.Bind("tcp://*:5563");

				int published = 0;
				while (true)
				{
					// Write two messages, each with an envelope and content

					using (var message = new ZMessage())
					{
						published++;
						message.Add(new ZFrame(string.Format("A {0}", published)));
						message.Add(new ZFrame(string.Format(" We don't like to see this.")));
						Thread.Sleep(1000);

						Console_WriteZMessage("Publishing ", message);
						publisher.Send(message);
					}

					using (var message = new ZMessage())
					{
						published++;
						message.Add(new ZFrame(string.Format("B {0}", published)));
						message.Add(new ZFrame(string.Format(" We do like to see this.")));
						Thread.Sleep(1000);

						Console_WriteZMessage("Publishing ", message);
						publisher.Send(message);
					}
				}
			}
		}
Exemplo n.º 37
0
		public static void FLClient3(string[] args)
		{
			//
			// Freelance client - Model 3
			// Uses FLCliApi.FreelanceClient class to encapsulate Freelance pattern
			//
			// Author: metadings
			//
			if (args == null || args.Length < 2)
			{
				Console.WriteLine();
				Console.WriteLine("Usage: ./{0} FLClient3 [Name] [Endpoint]", AppDomain.CurrentDomain.FriendlyName);
				Console.WriteLine();
				Console.WriteLine("    Name      Your Name");
				Console.WriteLine("    Endpoint  Where FLClient3 should connect to.");
				Console.WriteLine("              Default: tcp://127.0.0.1:5555");
				Console.WriteLine();
				if (args.Length < 1)
					args = new string[] { "World", "tcp://127.0.0.1:5555" };
				else
					args = new string[] { args[0], "tcp://127.0.0.1:5555" };
			}

			string name = args[0];

			// Create new freelance client object
			using (var client = new FreelanceClient())
			{
				// Connect to one or more endpoints
				for (int i = 0; i < args.Length - 1; ++i)
				{
					client.Connect(args[1]);
				}

				// Send a bunch of name resolution 'requests', measure time
				var stopwatch = new Stopwatch();
				stopwatch.Start();

				int requests = 0;
				while (requests++ < 100)
				{
					using (var request = new ZMessage())
					{
						request.Add(new ZFrame(name));

						using (ZMessage reply = client.Request(request))
						{

						}
					}
				}

				stopwatch.Stop();
				Console.WriteLine("Average round trip cost: {0} ms", stopwatch.ElapsedMilliseconds / requests);
			}
		}
Exemplo n.º 38
0
		static void AsyncSrv_Client(ZContext context, int i) 
		{
			//
			// Asynchronous client-to-server (DEALER to ROUTER)
			//
			// While this example runs in a single process, that is to make
			// it easier to start and stop the example. Each task has its own
			// context and conceptually acts as a separate process.
			//
			// Author: metadings
			//

			// This is our client task
			// It connects to the server, and then sends a request once per second
			// It collects responses as they arrive, and it prints them out. We will
			// run several client tasks in parallel, each with a different random ID.

			using (var client = new ZSocket(context, ZSocketType.DEALER))
			{
				// Set identity to make tracing easier
				client.Identity = Encoding.UTF8.GetBytes("CLIENT" + i);
				// Connect
				client.Connect("tcp://127.0.0.1:5570");

				ZError error;
				ZMessage incoming;
				var poll = ZPollItem.CreateReceiver();

				int requests = 0;
				while (true)
				{
					// Tick once per second, pulling in arriving messages
					for (int centitick = 0; centitick < 100; ++centitick)
					{
						if (!client.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(10)))
						{
							if (error == ZError.EAGAIN)
							{
								Thread.Sleep(1);
								continue;
							}
							if (error == ZError.ETERM)
								return;	// Interrupted
							throw new ZException(error);
						}
						using (incoming)
						{
							string messageText = incoming[0].ReadString();
							Console.WriteLine("[CLIENT{0}] {1}", i, messageText);
						}
					}
					using (var outgoing = new ZMessage())
					{
						outgoing.Add(new ZFrame(client.Identity));
						outgoing.Add(new ZFrame("request " + (++requests)));

						if (!client.Send(outgoing, out error))
						{
							if (error == ZError.ETERM)
								return;	// Interrupted
							throw new ZException(error);
						}
					}
				}
			}
		}
Exemplo n.º 39
0
		static void StreamDealer_Server(CancellationToken cancellus, int i, string name, bool doMonitor)
		{
			using (var socket = ZSocket.Create(context, ZSocketType.REP))
			{
				if (doMonitor) socket.Monitor("inproc://StreamDealer-Server" + i);

				socket.Connect(Backend);

				ZError error;
				ZMessage request;
				var poller = ZPollItem.CreateReceiver();

				while (!cancellus.IsCancellationRequested)
				{
					if (!socket.PollIn(poller, out request, out error, TimeSpan.FromMilliseconds(250)))
					{
						if (error == ZError.EAGAIN)
						{
							error = ZError.None;
							Thread.Sleep(1);

							continue;
						}

						throw new ZException(error);
					}

					using (request)
					using (var response = new ZMessage())
					{
						response.Add(new ZFrame(
@"HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8

<html>
<head>
	<title>Hello World!</title>
</head>
<body>
	<h3>Hello, I am " + name + @"!</h3>

	<div>Your IP:</div>
	<pre>" + request[0].ReadString() + @"</pre>

	<div>Your Request:</div>
	<pre>" + request[1].ReadString() + @"</pre>

	<button id=""btnStop"">Stop</button>
	<script type=""text/javascript"">
		(function () {

			var timeout = setTimeout(function () { location.reload(true); }, 1000);

			addEventListener(""click"", function () {
				clearTimeout(timeout);
				var btn = document.getElementById(""btnStop"");
				btn.parentNode.removeChild(btn);
			});

		}());
	</script>

</body>
</html>"));
						socket.Send(response);
					}
				}
			}
		}
Exemplo n.º 40
0
		static void PushPullDevice_Client(int j, string name, Action monitor = null)
		{
			using (var socket = ZSocket.Create(context, ZSocketType.PUSH))
			{
				if (monitor != null) { socket.Monitor("inproc://PushPullDevice-Client" + j); monitor(); }

				socket.Connect(Frontend);

				using (var request = new ZMessage())
				{
					request.Add(new ZFrame(name));

					socket.Send(request);
				}
			}
		}
Exemplo n.º 41
0
        /// <summary>
        /// Sends data to the server asynchronously.
        /// </summary>
        /// <param name="data">The buffer that contains the binary data to be sent.</param>
        /// <param name="offset">The zero-based position in the <paramref name="data"/> at which to begin sending data.</param>
        /// <param name="length">The number of bytes to be sent from <paramref name="data"/> starting at the <paramref name="offset"/>.</param>
        /// <returns><see cref="WaitHandle"/> for the asynchronous operation.</returns>
        protected override WaitHandle SendDataAsync(byte[] data, int offset, int length)
        {
            if (CurrentState != ClientState.Connected)
                throw new SocketException((int)SocketError.NotConnected);

            try
            {
                if ((object)m_zeroMQClient.Provider != null)
                {
                    using (ZMessage message = new ZMessage())
                    {
                        // Dealer socket will auto-add identity, just add delimiter and data payload frames
                        message.Add(new ZFrame());
                        message.Add(new ZFrame(data, offset, length));

                        // ZeroMQ send is asynchronous, but API call is not thread-safe
                        lock (m_sendLock)
                            m_zeroMQClient.Provider.Send(message);
                    }

                    m_zeroMQClient.Statistics.UpdateBytesSent(length);
                }
            }
            catch (Exception ex)
            {
                // Log exception during send operation
                OnSendDataException(ex);
            }

            return m_completedHandle.WaitHandle;
        }
Exemplo n.º 42
0
		static void RequestReply_Server(object cancelluS)
		{
			var cancellus = (CancellationToken)cancelluS;

			using (var socket = ZSocket.Create(context, ZSocketType.REP))
			{
				socket.Bind(Frontend);

				ZError error;
				ZMessage request = null;

				while (!cancellus.IsCancellationRequested)
				{
					if (!socket.ReceiveMessage(ref request, ZSocketFlags.DontWait, out error))
					{
						if (error == ZError.EAGAIN)
						{
							error = ZError.None;
							Thread.Sleep(1);

							continue;
						}

						throw new ZException(error);
					}

					// Let the response be "Hello " + input
					using (request)
					using (var response = new ZMessage())
					{
						response.Add(new ZFrame("Hello " + request[0].ReadString()));

						socket.Send(response);
					}

					request = null;
				}
			}
		}
Exemplo n.º 43
0
		public static void FLClient2(string[] args)
		{
			if (args == null || args.Length < 1)
			{
				Console.WriteLine();
				Console.WriteLine("Usage: ./{0} FLClient2 [Endpoint] ...", AppDomain.CurrentDomain.FriendlyName);
				Console.WriteLine();
				Console.WriteLine("    Endpoint  Where FLClient2 should connect to.");
				Console.WriteLine("              Default is tcp://127.0.0.1:7781");
				Console.WriteLine();
				args = new string[] { "tcp://127.0.0.1:7781" };
			}

			// Create new freelance client object
			using (var client = new FLClient())
			{
				// Connect to each endpoint
				for (int i = 0; i < args.Length; ++i)
				{
					client.Connect(args[i]);
				}

				// Send a bunch of name resolution 'requests', measure time
				int requests = 0;
				DateTime starttime = DateTime.UtcNow;
				var error = ZError.None;
				while (++requests < 10000)
				{
					var outgoing = new ZMessage();
					outgoing.Add(new ZFrame("random name"));

					ZMessage incoming = client.Request(outgoing);
					if (incoming == null)
					{
						error = ZError.ETERM;
						break;
					}
					incoming.Dispose(); // using (incoming) ;
				}

				if (error == ZError.ETERM)
					Console.WriteLine("E: name service not available, aborted.");

				else
					Console.WriteLine("Average round trip cost: {0} ms", (DateTime.UtcNow - starttime).TotalMilliseconds / requests);

			}
		}
Exemplo n.º 44
0
		static void PubSubDevice_Server(CancellationToken cancellus, int i, string name, bool doMonitor)
		{
			using (var socket = ZSocket.Create(context, ZSocketType.PUB))
			{
				if (doMonitor) socket.Monitor("inproc://PubSubDevice-Server" + i);

				socket.Connect(Frontend);

				var now = DateTime.Now;

				while (!cancellus.IsCancellationRequested)
				{
					if (now.AddSeconds(5) >= DateTime.Now)
					{
						Thread.Sleep(100);
						continue;
					}
					now = DateTime.Now;

					using (var response = new ZMessage())
					{
						response.Add(new ZFrame(
							string.Format("{0} {1}", DateTime.Now.ToString("G"), name)
						));

						socket.Send(response);
					}
				}

				socket.Disconnect(Frontend);
			}
		}
Exemplo n.º 45
0
		static void PubSub_Server(CancellationToken cancellus, string[] names)
		{
			using (var socket = ZSocket.Create(context, ZSocketType.PUB))
			{
				socket.Bind(Frontend);

				var now = DateTime.Now;
				var nameI = -1;

				while (!cancellus.IsCancellationRequested)
				{
					if (now.AddSeconds(5) >= DateTime.Now)
					{
						Thread.Sleep(1);
						continue;
					}
					now = DateTime.Now;
					++nameI;
					if (nameI == names.Length) {
						nameI = 0;
					}

					using (var response = new ZMessage())
					{
						response.Add(new ZFrame(DateTime.Now.ToString("G") + " " + names[nameI]));

						socket.Send(response);
					}
				}

				socket.Unbind(Frontend);
			}
		}
Exemplo n.º 46
0
		public static void LBBroker(string[] args)
		{
			// This is the main task. It starts the clients and workers, and then
			// routes requests between the two layers. Workers signal READY when
			// they start; after that we treat them as ready when they reply with
			// a response back to a client. The load-balancing data structure is
			// just a queue of next available workers.

			// Prepare our context and sockets
			using (var context = new ZContext())
			using (var frontend = new ZSocket(context, ZSocketType.ROUTER))
			using (var backend = new ZSocket(context, ZSocketType.ROUTER))
			{
				// Bind
				frontend.Bind("inproc://frontend");
				// Bind
				backend.Bind("inproc://backend");

				int clients = 0;
				for (; clients < LBBroker_Clients; ++clients)
				{
					int j = clients;
					new Thread(() => LBBroker_Client(context, j)).Start();
				}
				for (int i = 0; i < LBBroker_Workers; ++i)
				{
					int j = i;
					new Thread(() => LBBroker_Worker(context, j)).Start();
				}

				// Here is the main loop for the least-recently-used queue. It has two
				// sockets; a frontend for clients and a backend for workers. It polls
				// the backend in all cases, and polls the frontend only when there are
				// one or more workers ready. This is a neat way to use 0MQ's own queues
				// to hold messages we're not ready to process yet. When we get a client
				// reply, we pop the next available worker and send the request to it,
				// including the originating client identity. When a worker replies, we
				// requeue that worker and forward the reply to the original client
				// using the reply envelope.

				// Queue of available workers
				var worker_queue = new List<string>();

				ZMessage incoming;
				ZError error;
				var poll = ZPollItem.CreateReceiver();

				while (true)
				{
					if (backend.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(64)))
					{
						// Handle worker activity on backend

						// incoming[0] is worker_id
						string worker_id = incoming[0].ReadString();
						// Queue worker identity for load-balancing
						worker_queue.Add(worker_id);

						// incoming[1] is empty

						// incoming[2] is READY or else client_id
						string client_id = incoming[2].ReadString();

						if (client_id != "READY")
						{
							// incoming[3] is empty

							// incoming[4] is reply
							string reply = incoming[4].ReadString();

							using (var outgoing = new ZMessage())
							{
								outgoing.Add(new ZFrame(client_id));
								outgoing.Add(new ZFrame());
								outgoing.Add(new ZFrame(reply));

								// Send
								frontend.Send(outgoing);
							}

							if (--clients == 0)
							{
								// break the while (true) when all clients said Hello
								break;
							}
						}
					}
					if (worker_queue.Count > 0)
					{
						// Poll frontend only if we have available workers

						if (frontend.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(64)))
						{
							// Here is how we handle a client request

							// incoming[0] is client_id
							string client_id = incoming[0].ReadString();

							// incoming[1] is empty

							// incoming[2] is request
							string requestText = incoming[2].ReadString();

							using (var outgoing = new ZMessage())
							{
								outgoing.Add(new ZFrame(worker_queue[0]));
								outgoing.Add(new ZFrame());
								outgoing.Add(new ZFrame(client_id));
								outgoing.Add(new ZFrame());
								outgoing.Add(new ZFrame(requestText));

								// Send
								backend.Send(outgoing);
							}

							// Dequeue the next worker identity
							worker_queue.RemoveAt(0);
						}
					}
				}
			}
		}
Exemplo n.º 47
0
		static void AsyncSrv_ServerWorker(ZContext context, int i) 
		{
			// Each worker task works on one request at a time and sends a random number
			// of replies back, with random delays between replies:

			using (var worker = new ZSocket(context, ZSocketType.DEALER))
			{
				worker.Connect("inproc://backend");

				ZError error;
				ZMessage request;
				var rnd = new Random();

				while (true)
				{
					if (null == (request = worker.ReceiveMessage(out error)))
					{
						if (error == ZError.ETERM)
							return;	// Interrupted
						throw new ZException(error);
					}
					using (request)
					{
						// The DEALER socket gives us the reply envelope and message
						string identity = request[1].ReadString();
						string content = request[2].ReadString();

						// Send 0..4 replies back
						int replies = rnd.Next(5);
						for (int reply = 0; reply < replies; ++reply)
						{
							// Sleep for some fraction of a second
							Thread.Sleep(rnd.Next(1000) + 1);

							using (var response = new ZMessage())
							{
								response.Add(new ZFrame(identity));
								response.Add(new ZFrame(content));

								if (!worker.Send(response, out error))
								{
									if (error == ZError.ETERM)
										return;	// Interrupted
									throw new ZException(error);
								}
							}
						}
					}
				}
			}
		}
Exemplo n.º 48
0
		public static void FLServer3(string[] args)
		{
			//
			// Freelance server - Model 3
			// Uses an ROUTER/ROUTER socket but just one thread
			//
			// Author: metadings
			//

			// Prepare server socket with predictable identity
			string bind_endpoint = "tcp://*:5555";
			string connect_endpoint = "tcp://127.0.0.1:5555";

			using (var context = new ZContext())
			using (var server = new ZSocket(context, ZSocketType.ROUTER))
			{
				Console.CancelKeyPress += (s, ea) =>
				{
					ea.Cancel = true;
					context.Shutdown();
				};

				server.IdentityString = connect_endpoint;
				server.Bind(bind_endpoint);
				Console.WriteLine("I: service is ready as {0}", bind_endpoint);

				ZError error;
				ZMessage request;
				while (true)
				{
					if (null == (request = server.ReceiveMessage(out error)))
					{
						if (error == ZError.ETERM)
							break;	// Interrupted
						throw new ZException(error);
					}
					using (var response = new ZMessage())
					{
						ZFrame identity;

						using (request)
						{
							if (Verbose) Console_WriteZMessage("Receiving", request);

							// Frame 0: identity of client
							// Frame 1: PING, or client control frame
							// Frame 2: request body

							identity = request.Pop();

							ZFrame control = request.Pop();
							string controlMessage = control.ReadString();

							if (controlMessage == "PING")
							{
								control.Dispose();
								response.Add(new ZFrame("PONG"));
							}
							else
							{
								response.Add(control);
								response.Add(new ZFrame("OK"));
							}
						}

						response.Prepend(identity);

						if (Verbose) Console_WriteZMessage("Sending  ", response);
						if (!server.Send(response, out error))
						{
							if (error == ZError.ETERM)
								break;	// Interrupted
							throw new ZException(error);
						}
					}
				}
				if (error == ZError.ETERM)
				{
					Console.WriteLine("W: interrupted");
				}
			}
		}
Exemplo n.º 49
0
		static void LBBroker_Worker(ZContext context, int i)
		{
			// This is the worker task, using a REQ socket to do load-balancing.

			// Create socket
			using (var worker = new ZSocket(context, ZSocketType.REQ))
			{
				// Set a printable identity
				worker.IdentityString = "WORKER" + i;

				// Connect
				worker.Connect("inproc://backend");

				// Tell broker we're ready for work
				using (var ready = new ZFrame("READY"))
				{
					worker.Send(ready);
				}

				ZError error;
				ZMessage request;

				while (true)
				{
					// Get request
					if (null == (request = worker.ReceiveMessage(out error)))
					{
						// We are using "out error",
						// to NOT throw a ZException ETERM
						if (error == ZError.ETERM)
							break;

						throw new ZException(error);
					}

					using (request)
					{
						string worker_id = request[0].ReadString();

						string requestText = request[2].ReadString();
						Console.WriteLine("WORKER{0}: {1}", i, requestText);

						// Send reply
						using (var commit = new ZMessage())
						{
							commit.Add(new ZFrame(worker_id));
							commit.Add(new ZFrame());
							commit.Add(new ZFrame("OK"));

							worker.Send(commit);
						}
					}
				}
			}
		}
Exemplo n.º 50
0
		static void RouterDealer_Server(CancellationToken cancellus, int i, string name, bool doMonitor)
		{
			using (var socket = ZSocket.Create(context, ZSocketType.REP))
			{
				if (doMonitor) socket.Monitor("inproc://RouterDealer-Server" + i);

				socket.Connect(Backend);

				ZError error;
				ZMessage request = null;

				while (!cancellus.IsCancellationRequested)
				{
					if (!socket.ReceiveMessage(ref request, ZSocketFlags.DontWait, out error))
					{
						if (error == ZError.EAGAIN)
						{
							error = ZError.None;
							Thread.Sleep(1);

							continue;
						}

						throw new ZException(error);
					}

					using (request)
					using (var response = new ZMessage())
					{
						// Read the REQuest, Write the REPly
						response.Add(new ZFrame(name + " says hello to " + request[0].ReadString()));

						socket.Send(response);
					}

					request = null;
				}
			}
		}
Exemplo n.º 51
0
		static string RouterDealer_Client(int j, string name, Action monitor = null)
		{
			string output = null;

			using (var socket = ZSocket.Create(context, ZSocketType.REQ))
			{
				if (monitor != null) { socket.Monitor("inproc://RouterDealer-Client" + j); monitor(); }

				socket.Connect(Frontend);

				using (var request = new ZMessage())
				{
					// Append a ZFrame with the "name"
					request.Add(new ZFrame(name));

					// Send the REQuest
					socket.Send(request);
				}

				using (ZMessage response = socket.ReceiveMessage())
				{
					// Read the REPly
					output = response[0].ReadString();
				}
			}

			return output;
		}
Exemplo n.º 52
0
		//
		// Broker peering simulation (part 1)
		// Prototypes the state flow
		//
		// Author: metadings
		//

		public static void Peering1(string[] args)
		{
			// First argument is this broker's name
			// Other arguments are our peers' names
			//
			if (args == null || args.Length < 2)
			{
				Console.WriteLine();
				Console.WriteLine("Usage: {0} Peering1 World Receiver0", AppDomain.CurrentDomain.FriendlyName);
				Console.WriteLine("       {0} Peering1 Receiver0 World", AppDomain.CurrentDomain.FriendlyName);
				Console.WriteLine();
				return;
			}
			string self = args[0];
			Console.WriteLine("I: preparing broker as {0}", self);

			using (var context = new ZContext())
			using (var backend = new ZSocket(context, ZSocketType.PUB))
			using (var frontend = new ZSocket(context, ZSocketType.SUB))
			{
				// Bind backend to endpoint
				backend.Bind("tcp://127.0.0.1:" + Peering1_GetPort(self));

				// Connect frontend to all peers
				frontend.SubscribeAll();
				for (int i = 1; i < args.Length; ++i)
				{
					string peer = args[i];
					Console.WriteLine("I: connecting to state backend at {0}", peer);
					frontend.Connect("tcp://127.0.0.1:" + Peering1_GetPort(peer));
				}

				// The main loop sends out status messages to peers, and collects
				// status messages back from peers. The zmq_poll timeout defines
				// our own heartbeat:

				ZError error;
				ZMessage incoming;
				var poll = ZPollItem.CreateReceiver();
				var rnd = new Random();

				while (true)
				{
					// Poll for activity, or 1 second timeout
					if (!frontend.PollIn(poll, out incoming, out error, TimeSpan.FromSeconds(1)))
					{
						if (error == ZError.EAGAIN)
						{
							using (var output = new ZMessage())
							{
								output.Add(new ZFrame(self));

								var outputNumber = ZFrame.Create(4);
								outputNumber.Write(rnd.Next(10));
								output.Add(outputNumber);

								backend.Send(output);
							}

							continue;
						}
						if (error == ZError.ETERM)
							return;

						throw new ZException(error);
					}
					using (incoming)
					{
						string peer_name = incoming[0].ReadString();
						int available = incoming[1].ReadInt32();
						Console.WriteLine("{0} - {1} workers free", peer_name, available);
					}
				}
			}
		}
Exemplo n.º 53
0
            //  .split broker client_msg method
            //  Process a request coming from a client. We implement MMI requests
            //  directly here (at present, we implement only the mmi.service request):
            public void ClientMsg(ZFrame sender, ZMessage msg)
            {
                // service & body
                if(msg.Count < 2)
                    throw new InvalidOperationException();

                using (ZFrame serviceFrame = msg.Pop())
                {
                    Service service = RequireService(serviceFrame);

                    // Set reply return identity to client sender
                    msg.Wrap(sender.Duplicate());

                    //if we got a MMI Service request, process that internally
                    if (serviceFrame.Length >= 4
                        && serviceFrame.ToString().StartsWith("mmi."))
                    {
                        string returnCode;
                        if (serviceFrame.ToString().Equals("mmi.service"))
                        {
                            string name = msg.Last().ToString();
                            returnCode = Services.ContainsKey(name)
                                         && Services[name].Workers > 0
                                            ? "200"
                                            : "404";
                        }
                        else
                            returnCode = "501";

                        var client = msg.Unwrap();

                        msg.Clear();
                        msg.Add(new ZFrame(returnCode));
                        msg.Prepend(serviceFrame);
                        msg.Prepend(new ZFrame(MdpCommon.MDPC_CLIENT));

                        msg.Wrap(client);
                        Socket.Send(msg);
                    }
                    else
                    {
                        // Else dispatch the message to the requested Service
                        service.Dispatch(msg);
                    }
                }
            }
Exemplo n.º 54
0
		public static void SPQueue(string[] args)
		{
			//
			// Simple Pirate broker
			// This is identical to load-balancing pattern, with no reliability
			// mechanisms. It depends on the client for recovery. Runs forever.
			//
			// Author: metadings
			//

			using (var context = new ZContext())
			using (var frontend = new ZSocket(context, ZSocketType.ROUTER))
			using (var backend = new ZSocket(context, ZSocketType.ROUTER))
			{
				frontend.Bind("tcp://*:5555");
				backend.Bind("tcp://*:5556");

				// Queue of available workers
				var worker_queue = new List<string>();

				ZError error;
				ZMessage incoming;
				var poll = ZPollItem.CreateReceiver();

				while (true)
				{
					if (backend.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(64)))
					{
						using (incoming)
						{
							// Handle worker activity on backend

							// incoming[0] is worker_id
							string worker_id = incoming[0].ReadString();
							// Queue worker identity for load-balancing
							worker_queue.Add(worker_id);

							// incoming[1] is empty

							// incoming[2] is READY or else client_id
							string client_id = incoming[2].ReadString();

							if (client_id == "READY")
							{
								Console.WriteLine("I: ({0}) worker ready", worker_id);
							}
							else
							{
								// incoming[3] is empty

								// incoming[4] is reply
								// string reply = incoming[4].ReadString();
								// int reply = incoming[4].ReadInt32();

								Console.WriteLine("I: ({0}) work complete", worker_id);

								using (var outgoing = new ZMessage())
								{
									outgoing.Add(new ZFrame(client_id));
									outgoing.Add(new ZFrame());
									outgoing.Add(incoming[4]);

									// Send
									frontend.Send(outgoing);
								}
							}
						}
					}
					else
					{
						if (error == ZError.ETERM)
							return;
						if (error != ZError.EAGAIN)
							throw new ZException(error);
					}

					if (worker_queue.Count > 0)
					{
						// Poll frontend only if we have available workers

						if (frontend.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(64)))
						{
							using (incoming)
							{
								// Here is how we handle a client request

								// Dequeue the next worker identity
								string worker_id = worker_queue[0];
								worker_queue.RemoveAt(0);

								// incoming[0] is client_id
								string client_id = incoming[0].ReadString();

								// incoming[1] is empty

								// incoming[2] is request
								// string request = incoming[2].ReadString();
								int request = incoming[2].ReadInt32();

								Console.WriteLine("I: ({0}) working on ({1}) {2}", worker_id, client_id, request);

								using (var outgoing = new ZMessage())
								{
									outgoing.Add(new ZFrame(worker_id));
									outgoing.Add(new ZFrame());
									outgoing.Add(new ZFrame(client_id));
									outgoing.Add(new ZFrame());
									outgoing.Add(incoming[2]);

									// Send
									backend.Send(outgoing);
								}
							}
						}
						else
						{
							if (error == ZError.ETERM)
								return;
							if (error != ZError.EAGAIN)
								throw new ZException(error);
						}
					}
				}
			}
		}
Exemplo n.º 55
0
        private void MainLoop()
        {
            ZError error;
            ZMessage incoming;
            var poll = ZPollItem.CreateReceiver();

            while (true)
            {
                //await Task.Delay(1);
                //yield return null;

                if (_backendSocket.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(1)))
                {
                    using (incoming)
                    {
                        // Handle worker activity on backend

                        // incoming[0] is worker_id
                        string workerName = incoming[0].ReadString();
                        // Queue worker identity for load-balancing
                        workerQueue.Add(workerName);

                        // incoming[1] is empty

                        // incoming[2] is READY or else client_id
                        var client_id = incoming[2];
                        var clientIdString = client_id.ToString();
                        if (client_id.ToString() == "READY")
                        {
                            Logger.Warn("I: ({0}) worker ready!!!", workerName);
                        }
                        else
                        {
                            // incoming[3] is empty
                            // incoming[4] is reply
                            // string reply = incoming[4].ReadString();
                            // int reply = incoming[4].ReadInt32();

                            Logger.Trace("I: ({0}) work complete", workerName);

                            using (var outgoing = new ZMessage())
                            {
                                outgoing.Add(client_id);
                                outgoing.Add(new ZFrame());
                                outgoing.Add(incoming[4]);

                                // Send
                                _responseSocket.Send(outgoing);
                            }
                        }
                    }
                }
                else
                {
                    if (error == ZError.ETERM)
                        return;
                        //yield break;
                    if (error != ZError.EAGAIN)
                        throw new ZException(error);
                }

                if (workerQueue.Count > 0)
                {
                    // Poll frontend only if we have available workers
                    if (_responseSocket.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(1)))
                    {
                        using (incoming)
                        {
                            // Here is how we handle a client request

                            // Dequeue the next worker identity
                            string workerId = workerQueue[0];
                            workerQueue.RemoveAt(0);

                            // incoming[0] is client_id
                            var client_id = incoming[0];
                            var clientIdStr = client_id.ToString();
                            // incoming[1] is empty

                            // incoming[2] is request
                            // string request = incoming[2].ReadString();
                            var requestData = incoming[2];

                            Logger.Trace("I: ({0}) working on ({1}) {2}", workerId, client_id, requestData);

                            using (var outgoing = new ZMessage())
                            {
                                outgoing.Add(new ZFrame(workerId));
                                outgoing.Add(new ZFrame());
                                outgoing.Add(client_id);
                                outgoing.Add(new ZFrame());
                                outgoing.Add(requestData);

                                // Send
                                _backendSocket.Send(outgoing);
                            }
                        }
                    }
                    else
                    {
                        if (error == ZError.ETERM)
                            return;
                            //yield break;
                        if (error != ZError.EAGAIN)
                            throw new ZException(error);
                    }
                }
                else
                {
                    //Logger.Warn("no idle worker....");
                    //AddWorker(); // 不够worker,创建一个
                }
            }
        }
Exemplo n.º 56
0
			public void Connect(string endpoint)
			{
				// To implement the connect method, the frontend object sends a multipart
				// message to the backend agent. The first part is a string "CONNECT", and
				// the second part is the endpoint. It waits 100msec for the connection to
				// come up, which isn't pretty, but saves us from sending all requests to a
				// single server, at startup time:

				using (var message = new ZMessage())
				{
					message.Add(new ZFrame("CONNECT"));
					message.Add(new ZFrame(endpoint));

					this.Actor.Frontend.Send(message);
				}

				Thread.Sleep(64);	// Allow connection to come up
			}
Exemplo n.º 57
0
		static string RequestReply_Client(string name)
		{
			string output = null;

			using (var socket = ZSocket.Create(context, ZSocketType.REQ))
			{
				socket.Connect(Frontend);

				using (var request = new ZMessage())
				{
					request.Add(new ZFrame(name));

					socket.Send(request);
				}

				using (ZMessage response = socket.ReceiveMessage())
				{
					output = response[0].ReadString();
				}
			}

			return output;
		}
Exemplo n.º 58
0
			public void Ping(ZSocket socket)
			{
				if (DateTime.UtcNow >= PingAt)
				{
					using (var outgoing = new ZMessage())
					{
						outgoing.Add(new ZFrame(Endpoint));
						outgoing.Add(new ZFrame("PING"));

						socket.Send(outgoing);
					}

					this.PingAt = DateTime.UtcNow + PING_INTERVAL;
				}
			}
Exemplo n.º 59
0
		static void PushPull_Client(string name)
		{
			using (var socket = ZSocket.Create(context, ZSocketType.PUSH))
			{
				socket.Connect(Frontend);

				using (var request = new ZMessage())
				{
					request.Add(new ZFrame(name));

					socket.Send(request);
				}
			}
		}
Exemplo n.º 60
0
        /// <summary>
        /// Sends data to the specified client asynchronously.
        /// </summary>
        /// <param name="clientID">ID of the client to which the data is to be sent.</param>
        /// <param name="data">The buffer that contains the binary data to be sent.</param>
        /// <param name="offset">The zero-based position in the <paramref name="data"/> at which to begin sending data.</param>
        /// <param name="length">The number of bytes to be sent from <paramref name="data"/> starting at the <paramref name="offset"/>.</param>
        /// <returns><see cref="WaitHandle"/> for the asynchronous operation.</returns>
        protected override WaitHandle SendDataToAsync(Guid clientID, byte[] data, int offset, int length)
        {
            if (CurrentState != ServerState.Running)
                throw new SocketException((int)SocketError.NotConnected);

            try
            {
                if ((object)m_zeroMQServer != null)
                {
                    // Lookup client info, adding it if it doesn't exist
                    TransportProvider<DateTime> clientInfo = GetClient(clientID);

                    // Router socket should provide identity, delimiter and data payload frames
                    using (ZMessage message = new ZMessage())
                    {
                        // Add identity, delimiter and data payload frames
                        message.Add(new ZFrame(clientID.ToByteArray()));
                        message.Add(new ZFrame());
                        message.Add(new ZFrame(data, offset, length));

                        // ZeroMQ send is asynchronous, but API call is not thread-safe
                        lock (m_sendLock)
                            m_zeroMQServer.Send(message);
                    }

                    clientInfo.Statistics.UpdateBytesSent(length);

                    // Update last client activity time
                    clientInfo.Provider = DateTime.UtcNow;
                }
            }
            catch (Exception ex)
            {
                // Log exception during send operation
                OnSendClientDataException(clientID, ex);
            }

            return m_completedHandle.WaitHandle;
        }