Beispiel #1
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();
            }
        }
Beispiel #2
0
        //  ---------------------------------------------------------------------
        //  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.
        static void ClientTask()
        {
            using (Context ctx = new Context(1)) {
                using (Socket client = ctx.Socket(SocketType.XREQ)) {
                    //  Generate printable identity for the client
                    ZHelpers.SetID(client, Encoding.Unicode);
                    string identity = client.IdentityToString(Encoding.Unicode);
                    client.Connect("tcp://localhost:5570");

                    client.PollInHandler += (skt, revents) => {
                        ZMessage zmsg = new ZMessage(skt);
                        Console.WriteLine("{0} : {1}", identity, zmsg.BodyToString());
                    };

                    int requestNbr = 0;
                    while (true)
                    {
                        //  Tick once per second, pulling in arriving messages
                        for (int centitick = 0; centitick < 100; centitick++)
                        {
                            Context.Poller(new List <Socket>(new Socket[] { client }), 10000);
                        }
                        ZMessage zmsg = new ZMessage("");
                        zmsg.StringToBody(String.Format("request: {0}", ++requestNbr));
                        zmsg.Send(client);
                    }
                }
            }
        }
Beispiel #3
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();
            }
        }
Beispiel #4
0
        //  Majordomo Protocol client example
        //  Uses the mdcli API to hide all MDP aspects
        public static void MDClient2(string[] args)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            Console.CancelKeyPress += (s, ea) =>
            {
                ea.Cancel = true;
                cts.Cancel();
            };

            using (MajordomoClient session = new MajordomoClient("tcp://127.0.0.1:5555", Verbose))
            {
                int count;
                for (count = 0; count < 100000 && !cts.IsCancellationRequested; count++)
                {
                    ZMessage request = new ZMessage();
                    request.Prepend(new ZFrame("Hello world"));
                    session.Send("echo", request, cts);
                }
                for (count = 0; count < 100000 && !cts.IsCancellationRequested; count++)
                {
                    using (ZMessage reply = session.Recv(cts))
                        if (reply == null)
                            break; // Interrupt or failure
                }
                Console.WriteLine("{0} replies received\n", count);
            }
        }
Beispiel #5
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
                    }
                }
            }
        }
Beispiel #6
0
        private T DeserializeMessage <T>(ZMessage msg) where T : class
        {
            T             t         = null;
            ByteArrayPool _bytePool = new ByteArrayPool();

            byte[] tmp = _bytePool.Malloc((int)(msg[1].Length));
            msg[1].Read(tmp, 0, (int)(msg[1].Length));
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream(tmp))
            {
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter fmt = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                t = fmt.Deserialize(stream) as T;
            }
            _bytePool.Free(tmp);
            //try
            //{
            //    t = CommonUtils.FromJSON<T>(msg[1].ReadString());
            //}
            //catch (Exception ex)
            //{
            //    Program.logger.LogRunning("反序列化市场数据失败!\r\n  Message:{0}\r\n  StackTrace:{1}", ex.Message, ex.StackTrace);
            //}

            msg.Dispose();
            return(t);
        }
Beispiel #7
0
        private void InitHistoryOrder()
        {
            ZMessage connectMsg = new ZMessage();

            connectMsg.Add(new ZFrame("4|" + CommonUtils.Mac));
            lock (Sync)
            {
                try
                {
                    reqSocket.Send(connectMsg);
                    var msgResult = reqSocket.ReceiveMessage();

                    var list = msgResult[0].ReadString().FromJson <List <CATSEntity.StandardOrderEntity> >();
                    if (list.Count > 0)
                    {
                        Program.logger.LogInfo("CATS历史委托总数:{0}", list.Count);
                        list = list.Where(_ => _.OrderTime >= DateTime.Today).ToList();
                    }
                    else
                    {
                        Program.logger.LogInfo("CATS接口历史委托为空");
                    }
                    bagOrdersChangeList.Add(list);
                }
                catch (Exception ex)
                {
                    Program.logger.LogInfo("CATSAdapter.InitHistoryOrder Exception, {0}", ex.Message);
                }
            }
        }
Beispiel #8
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)));
     }
 }
Beispiel #9
0
        private void KeepAlive()
        {
            string sendMsgFormat = string.Format("10|{0}", CommonUtils.Mac);

            ZMessage msg = new ZMessage();

            msg.Add(new ZFrame(sendMsgFormat));
            lock (Sync)
            {
                try
                {
                    reqSocket.Send(msg);
                    var msgResult = reqSocket.ReceiveMessage();
                    var strResult = msgResult[0].ReadString();
                    if (strResult == "1")
                    {
                        HeartBreakResult = (DateTime.Now - dtKeepAlivePoint).TotalSeconds.ToString();
                        dtKeepAlivePoint = DateTime.Now;
                        return;
                    }
                    else
                    {
                        HeartBreakResult = strResult;
                        Program.logger.LogInfoDetail("心跳连接异常信息!返回结果{0}", strResult);
                    }
                }
                catch
                {
                    //this.isServerConnected = false;
                }
            }
        }
Beispiel #10
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);
                }
            }
        }
Beispiel #11
0
        private void SwitchMessage(ZMessage zMsgReply, string message, string[] info)
        {
            string traderName = info[1];
            ShareLimitGroupItem shareLimitGroup = ShareLimitAdapter.Instance.GetLimitGroup(traderName);

            switch (info[0])
            {
            case "1":     // 策略端发送指令格式:        1|交易员id|股票编码|开/平|开仓价格|股数  .     开/平:OPEN\CLOSE;  code:股票编码
                SendOrderMessageInit(zMsgReply, info, traderName, shareLimitGroup);
                break;

            case "2":
                CancelOrderMessageInit(zMsgReply, info, traderName);
                break;

            case "3":     // 查询 额度分配,订单,委托 3|交易员id|订单json|委托json
                QueryOrderMessageInit(zMsgReply, traderName);
                break;

            case "5":
                LimitQueryMessageInit(zMsgReply, traderName, shareLimitGroup);
                break;

            default:
                zMsgReply.Add(new ZFrame("Invalid Message, Not Implement branch, branch Value:" + info[0] + "\r\n  Total Message:" + message));
                break;
            }
        }
        public static bool Send(ZSocket socket, byte[] identity, string message, string uid, string messageType, string senderAddr, string receiverAddr)
        {
            ZError error;

            using (var outgoing = new ZMessage())
            {
                outgoing.Add(new ZFrame(identity));
                outgoing.Add(new ZFrame(message));
                outgoing.Add(new ZFrame(uid));
                outgoing.Add(new ZFrame(messageType));
                if (senderAddr != null)
                {
                    outgoing.Add(new ZFrame(senderAddr));
                }
                if (receiverAddr != null)
                {
                    outgoing.Add(new ZFrame(receiverAddr));
                }

                if (!socket.Send(outgoing, ZSocketFlags.DontWait, out error))
                {
                    ErrorChecker(error);
                    return(false);
                }
                return(true);
            }
        }
        //从流中读取完整ZMessage对象
        /// <summary>
        /// 从缓冲区中读初一条完整消息
        /// </summary>
        /// <param name="msg">读出的完整消息</param>
        /// <returns>如果为true,读取了完整消息</returns>
        public bool ReadMessage(out ZMessage msg)
        {
            ZMessage temp = new ZMessage();
            if (length >= 5)
            {
                MemoryStream stream = new MemoryStream(buffer);
                BinaryReader reader = new BinaryReader(stream);

                temp.head = reader.ReadByte();
                temp.length = reader.ReadInt32();

                if (temp.length <= (length - 5))
                {
                    temp.content = reader.ReadBytes(temp.length);
                    reader.Close();
                    Remove(temp.length + 5);
                    msg = temp;
                    return true;
                }
                else
                {
                    msg = null;
                    return false;
                }

            }
            else
            {
                msg = null;
                return false;
            }
        }
Beispiel #14
0
            public void RouterMessage(ZMessage reply)
            {
                // This method processes one message from a connected
                // server:

                // Frame 0 is server that replied
                string endpoint = reply.PopString();
                Server server   = this.Servers.Single(s => s.Endpoint == endpoint);

                if (!server.Alive)
                {
                    this.Actives.Add(server);
                    server.Refresh(true);
                }

                // Frame 1 may be sequence number for reply
                int sequence = reply.PopInt32();

                if (sequence == this.sequence)
                {
                    reply.Prepend(new ZFrame("OK"));

                    this.Pipe.Send(reply);

                    this.Request.Dispose();
                    this.Request = null;
                }
            }
Beispiel #15
0
        //  Majordomo Protocol worker example
        //  Uses the mdwrk API to hide all MDP aspects
        public static void MDWorker(string[] args)
        {
            bool verbose = (args.Any(e => e.ToLower().Equals("-v") ||
                                     e.ToLower().Equals("--verbose")));

            Console.WriteLine("Verbose: {0}", verbose);

            CancellationTokenSource cts = new CancellationTokenSource();

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

            using (MajordomoWorker session = new MajordomoWorker("tcp://127.0.0.1:5555", "echo", verbose))
            {
                ZMessage reply = null;
                while (true)
                {
                    ZMessage request = session.Recv(reply, cts);
                    if (request == null)
                    {
                        break;                         // worker was interrupted
                    }
                    reply = request;                   // Echo is complex
                }
            }
        }
Beispiel #16
0
        public static void Main(string[] args)
        {
            using (var context = new ZContext())
                using (var subscriber = new ZSocket(context, ZSocketType.SUB))
                {
                    subscriber.Connect("tcp://127.0.0.1:5555");
                    subscriber.Subscribe("A");

                    int subscribed = 0;
                    while (true)
                    {
                        using (ZMessage message = subscriber.ReceiveMessage())
                        {
                            subscribed++;

                            // Read envelope with address
                            string address = message[0].ReadString();

                            // Read message contents
                            string contents = message[1].ReadString();

                            Console.WriteLine("{0}. [{1}] {2}", subscribed, address, contents);
                        }
                    }
                }
        }
Beispiel #17
0
            protected void Dispose(bool disposing)
            {
                if (disposing)
                {
                    // Destructor

                    this.Servers = null;
                    this.Actives = null;

                    if (this.Request != null)
                    {
                        this.Request.Dispose();
                        this.Request = null;
                    }

                    /* if (this.reply != null)
                     * {
                     *      this.reply.Dispose();
                     *      this.reply = null;
                     * } */

                    if (this.Router != null)
                    {
                        this.Router.Dispose();
                        this.Router = null;
                    }
                }
            }
Beispiel #18
0
        //  Majordomo Protocol client example
        //  Uses the mdcli API to hide all MDP aspects
        static void Main(string[] args)
        {
            CancellationTokenSource cts = new CancellationTokenSource();

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

            using (MajordomoClient session = new MajordomoClient("tcp://127.0.0.1:5555", ProgramerHelper.Verbose))
            {
                int count;
                for (count = 0; count < 100000; count++)
                {
                    ZMessage request = new ZMessage();
                    request.Prepend(new ZFrame("Hello world"));

                    using (ZMessage reply = session.Send("echo", request, cts))
                        if (reply == null)
                        {
                            break;
                        }          // Interrupt or failure
                }
                Console.WriteLine("{0} requests/replies processed\n", count);
            }
        }
Beispiel #19
0
        public static void PSEnvPub(IDictionary <string, string> dict, string[] args)
        {
            //
            // Pubsub envelope publisher
            //
            // Author: metadings
            //

            // Prepare our context and publisher
            using (var context = ZContext.Create())
                using (var publisher = ZSocket.Create(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);
                    }
                }
        }
Beispiel #20
0
 //  Calls a TSP service
 //  Returns response if successful (status code 200 OK), else NULL
 static ZMessage TIClient_ServiceCall(MajordomoClient session, string service, ZMessage request, CancellationTokenSource cts)
 {
     using (var reply = session.Send(service, request, cts))
     {
         if (reply != null)
         {
             var status = reply.PopString();
             if (status.Equals("200"))
             {
                 return reply.Duplicate();
             }
             else if (status.Equals("400"))
             {
                 "E: client fatal error, aborting".DumpString();
                 cts.Cancel();
             }
             else if (status.Equals("500"))
             {
                 "E: server fatal error, aborting".DumpString();
                 cts.Cancel();
             }
         }
         else
         {
             cts.Cancel();   // Interrupted or failed
         }
     }
     return null;
 }
Beispiel #21
0
        public void GetRecordedOrder(string account, List <string> lstOrder)
        {
            lock (Sync)
            {
                string sendMsgFormat = string.Format("5|{0}|{1}", account, lstOrder.ToJson());

                try
                {
                    ZMessage msg = new ZMessage();
                    msg.Add(new ZFrame(sendMsgFormat));
                    reqSocket.Send(msg);
                    var msgResult = reqSocket.ReceiveMessage();
                    var strResult = msgResult[0].ReadString();
                    if (!string.IsNullOrEmpty(strResult))
                    {
                        var list = strResult.FromJson <List <CATSEntity.StandardOrderEntity> >();
                        if (list != null && list.Count > 0 && bagOrdersChangeList != null)
                        {
                            bagOrdersChangeList.Add(list);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Program.logger.LogInfo("CATSAdapter.GetRecordedOrder Exception : {0}", ex.Message);
                }
            }
        }
Beispiel #22
0
        private Tuple <ZMonitorEvents, object> CheckMonitor(ZSocket monitor)
        {
            try
            {
                ZMessage msg = new ZMessage();
                ZError   err;
                monitor.ReceiveMessage(ref msg, ZSocketFlags.DontWait, out err);
                if (err == ZError.EAGAIN)
                {
                    return(null);
                }

                var id  = msg[0].ReadUInt16();
                var val = msg[0].ReadUInt32();

                var data = new byte[msg[1].Length];
                msg[1].Read(data, 0, data.Length);

                return(new Tuple <ZMonitorEvents, object>((ZMonitorEvents)id, val));
            }
            catch (ZException)
            {
                return(null);
            }
        }
Beispiel #23
0
        //消息订阅者,对应发布者过滤消息
        public static void PSEnvSub(string[] args)
        {
            //
            // Pubsub envelope subscriber
            //
            // Author: metadings
            //

            // Prepare our context and subscriber
            using (var context = new ZContext())
                using (var subscriber = new ZSocket(context, ZSocketType.SUB))
                {
                    subscriber.Connect("tcp://127.0.0.1:5563");
                    subscriber.Subscribe("A");

                    int subscribed = 0;
                    while (true)
                    {
                        using (ZMessage message = subscriber.ReceiveMessage())
                        {
                            subscribed++;

                            // Read envelope with address
                            string address = message[0].ReadString();

                            // Read message contents
                            string contents = message[1].ReadString();

                            Console.WriteLine($"address:{address},contents:{contents}");
                        }
                    }
                }
        }
Beispiel #24
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();
                }
            }
        }
Beispiel #25
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);
        }
Beispiel #26
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());
				}
			}
		}
Beispiel #27
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());
                }
            }
        }
Beispiel #28
0
        private void ReceiveDataHandler()
        {
            while (Enabled)
            {
                // Receive data from the socket
                using (ZMessage message = m_zeroMQClient.Provider.ReceiveMessage())
                {
                    // Dealer socket should have removed identity frame already, should be left
                    // with delimiter and data payload frames
                    if (message.Count == 2)
                    {
                        // Get the data payload frame
                        ZFrame frame = message[1];

                        m_zeroMQClient.BytesReceived = (int)frame.Length;

                        if (m_zeroMQClient.ReceiveBufferSize < m_zeroMQClient.BytesReceived)
                        {
                            m_zeroMQClient.SetReceiveBuffer(m_zeroMQClient.BytesReceived);
                        }

                        frame.Read(m_zeroMQClient.ReceiveBuffer, 0, m_zeroMQClient.BytesReceived);

                        m_zeroMQClient.Statistics.UpdateBytesReceived(m_zeroMQClient.BytesReceived);

                        // Notify consumer of received data
                        OnReceiveDataComplete(m_zeroMQClient.ReceiveBuffer, m_zeroMQClient.BytesReceived);
                    }
                }
            }
        }
        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;
            }
        }
Beispiel #30
0
    private void ProcessMessage(ZMessage msg)
    {
        // extract frames
        var topic = msg[0].ToString(Encoding.UTF8);
        var flags = msg[1].ReadUInt32();
        var data  = msg[2].Read();
        var sent  = DateTimeOffset.FromUnixTimeMilliseconds(msg[3].ReadInt64()).DateTime;

        // compressed
        if ((flags & 1) == 1)
        {
            using (var stm = new MemoryStream(data))
            {
                using (var stmOut = new MemoryStream())
                {
                    using (var ds = new DeflateStream(stm, CompressionMode.Decompress))
                    {
                        ds.CopyTo(stmOut);
                    }

                    data = stmOut.ToArray();
                }
            }
        }

        // convert
        var content = Encoding.UTF8.GetString(data);

        // publish
        messageBus.SendMessage(new BtStreamMessage(topic, content, sent, DateTime.UtcNow));
    }
Beispiel #31
0
        //  ---------------------------------------------------------------------
        //  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.
        static void ClientTask()
        {
            using (Context ctx = new Context(1)) {
                using (Socket client = ctx.Socket(SocketType.XREQ)) {
                    //  Generate printable identity for the client
                    ZHelpers.SetID(client, Encoding.Unicode);
                    string identity = client.IdentityToString(Encoding.Unicode);
                    client.Connect("tcp://localhost:5570");

                    client.PollInHandler += (skt, revents) => {
                        ZMessage zmsg = new ZMessage(skt);
                        Console.WriteLine("{0} : {1}", identity, zmsg.BodyToString());
                    };

                    int requestNbr = 0;
                    while (true) {
                        //  Tick once per second, pulling in arriving messages
                        for (int centitick = 0; centitick < 100; centitick++) {
                            Context.Poller(new List<Socket>(new Socket[] { client }), 10000);
                        }
                        ZMessage zmsg = new ZMessage("");
                        zmsg.StringToBody(String.Format("request: {0}", ++requestNbr));
                        zmsg.Send(client);
                    }
                }
            }
        }
Beispiel #32
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);
                }
            }
        }
Beispiel #33
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);
                        }
                    }
                }
            }
        }
Beispiel #34
0
        private static void WorkerTask()
        {
            using (var ctx = new Context(1))
            {
                using (var worker = ctx.Socket(SocketType.REQ))
                {
                    ZHelpers.SetID(worker, Encoding.Unicode);
                    worker.Connect(localBeAddress);

                    var msg = new ZMessage("READY");
                    msg.Send(worker);

                    while (true)
                    {
                        var recvMsg = new ZMessage(worker);
                        Console.WriteLine("Worker: {0}", recvMsg.BodyToString());

                        Thread.Sleep(1000);

                        recvMsg.StringToBody("OK");
                        recvMsg.Send(worker);
                        //var okmsg = new ZMessage("OK");
                        //okmsg.Send(worker);
                    }
                }
            }
        }
Beispiel #35
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);
            }
        }
Beispiel #36
0
		//  Majordomo Protocol client example
		//  Uses the mdcli API to hide all MDP aspects
		public static void MDClient(string[] args)
		{
			bool verbose = (args.Any(e => e.ToLower().Equals("-v")
									   || e.ToLower().Equals("--verbose")));
			Console.WriteLine("Verbose: {0}", verbose);

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

			using (MajordomoClient session = new MajordomoClient("tcp://127.0.0.1:5555", verbose))
			{
				int count;
				for (count = 0; count < 100000; count++)
				{
					ZMessage request = new ZMessage();
					request.Prepend(new ZFrame("Hello world"));
					using (ZMessage reply = session.Send("echo", request, cts))
						if (reply == null)
							break; // Interrupt or failure
				}
				Console.WriteLine("{0} requests/replies processed\n", count);
			}
		}
Beispiel #37
0
 public static MessageData DecodeMessage(ZMessage message) =>
 new MessageData
 {
     Identity = message.Pop().ReadInt32(),
     Type     = (MessageType)message.Pop().ReadAsByte(),
     Data     = message.Select((frame) => frame.Read()).ToArray()
 };
Beispiel #38
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();
                }
            }
        }
Beispiel #39
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);
            }
        }
Beispiel #40
0
        public VehicleRecogResult GetVehicleByPic(string imageFileName)
        {
            VehicleRecogResult vehicleResults = new VehicleRecogResult();

            using (var requester = new ZSocket(context, ZSocketType.REQ))
            {
                requester.Connect("tcp://127.0.0.1:50559");
                string imagepath = imageFileName;
                if (File.Exists(imagepath))
                {
                    Guid guid = Guid.NewGuid();
                    DataTypes.VehicleInfo info = new DataTypes.VehicleInfo();
                    info.Id        = "11111";
                    info.Imagepath = (imagepath);
                    info.Uuid      = guid.ToString().Replace("-", "");
                    ZMessage zMsg = new ZMessage();
                    zMsg.Add(new ZFrame(info.ToByteArray()));
                    requester.Send(zMsg);
                    using (ZFrame reply = requester.ReceiveFrame())
                    {
                        DataTypes.VehicleInfo msg2 = new DataTypes.VehicleInfo();
                        msg2.MergeFrom(reply.Read());
                        vehicleResults = JsonConvert.DeserializeObject <VehicleRecogResult>(msg2.Jsonresult);

                        //Console.WriteLine(" Received:  {0}!", msg2.Jsonresult);
                    }
                }
            }

            return(vehicleResults);
        }
Beispiel #41
0
        static void Main(string[] args)
        {
            using (var context = ZmqContext.Create())
            {
                using (ZmqSocket frontend = context.CreateSocket(SocketType.ROUTER), backend = context.CreateSocket(SocketType.ROUTER))
                {
                    frontend.Bind("tcp://*:5555"); // For Clients
                    backend.Bind("tcp://*:5556"); // For Workers

                    //  Logic of LRU loop
                    //  - Poll backend always, frontend only if 1+ worker ready
                    //  - If worker replies, queue worker as ready and forward reply
                    //    to client if necessary
                    //  - If client requests, pop next worker and send request to it

                    //  Queue of available workers
                    var workerQueue = new Queue<byte[]>();

                    //  Handle worker activity on backend
                    backend.ReceiveReady += (s, e) =>
                                                 {
                                                     var zmsg = new ZMessage(e.Socket);
                                                     //  Use worker address for LRU routing
                                                     workerQueue.Enqueue(zmsg.Unwrap());

                                                     //  Forward message to client if it's not a READY
                                                     if (!Encoding.Unicode.GetString(zmsg.Address).Equals(LRU_READY))
                                                     {
                                                         zmsg.Send(frontend);
                                                     }
                                                 };

                    frontend.ReceiveReady += (s, e) =>
                                                  {
                                                      //  Now get next client request, route to next worker
                                                      //  Dequeue and drop the next worker address
                                                      var zmsg = new ZMessage(e.Socket);
                                                      zmsg.Wrap(workerQueue.Dequeue(), new byte[0]);
                                                      zmsg.Send(backend);
                                                  };

                    var poller = new Poller(new ZmqSocket[] { frontend, backend });

                    while (true)
                    {
                        //int rc = ZmqContext.Poller(workerQueue.Count > 0
                        //                            ? new List<ZmqSocket>(new ZmqSocket[] {frontend, backend})
                        //                            : new List<ZmqSocket>(new ZmqSocket[] {backend}));

                        int rc = poller.Poll();

                        if (rc == -1)
                        {
                            break;
                        }
                    }
                }
            }
        }
Beispiel #42
0
 public static bool PollOut(this ZSocket socket, ZPollItem item, ZMessage outgoing, out ZError error, TimeSpan? timeout = null)
 {
     if (outgoing == null)
     {
         throw new ArgumentNullException("outgoing");
     }
     return Poll(socket, item, ZPoll.Out, ref outgoing, out error, timeout);
 }
Beispiel #43
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);
			}
		}
        public void Publish(Type type, byte[] message, Dictionary<string, string> headers = null)
        {
            Dictionary<string, object> messageHeaders = GetHeaders(type, headers, _transportSettings.QueueName, "Publish");
            var serializedHeaders = JsonConvert.SerializeObject(messageHeaders);

            var msg = new ZMessage();
            msg.Append(new ZFrame(type.FullName.Replace(".", string.Empty)));
            msg.Append(new ZFrame(serializedHeaders));
            msg.Append(new ZFrame(message));

            _publisher.SendMessage(msg);
        }
Beispiel #45
0
		internal static bool PollSingleResult(ZSocket socket, ZPollItem item, ZPoll pollEvents, ref ZMessage message)
		{
			bool shouldReceive = item.ReceiveMessage != null && ((pollEvents & ZPoll.In) == ZPoll.In);
			bool shouldSend = item.SendMessage != null && ((pollEvents & ZPoll.Out) == ZPoll.Out);

			if (pollEvents == ZPoll.In)
			{

				if (!shouldReceive)
				{
					throw new InvalidOperationException("No ReceiveMessage delegate set for Poll.In");
				}

				if (OnReceiveMessage(socket, item, out message))
				{

					if (!shouldSend)
					{
						return true;
					}

					if (OnSendMessage(socket, item, message))
					{
						return true;
					}
				}
			}
			else if (pollEvents == ZPoll.Out)
			{

				if (!shouldSend)
				{
					throw new InvalidOperationException("No SendMessage delegate set for Poll.Out");
				}

				if (OnSendMessage(socket, item, message))
				{

					if (!shouldReceive)
					{
						return true;
					}

					if (OnReceiveMessage(socket, item, out message))
					{
						return true;
					}
				}
			}
			return false;
		}
Beispiel #46
0
        public static bool Poll(this ZSocket socket, ZPollItem item, ZPoll pollEvents, ref ZMessage message, out ZError error, TimeSpan? timeout = null)
        {
            if (PollSingle(socket, item, pollEvents, out error, timeout))
            {

                if (PollSingleResult(socket, item, pollEvents, ref message))
                {

                    return true;
                }
                error = ZError.EAGAIN;
            }
            return false;
        }
Beispiel #47
0
        public static bool Poll(this IEnumerable<ZSocket> sockets, IEnumerable<ZPollItem> items, ZPoll pollEvents, ref ZMessage[] messages, out ZError error, TimeSpan? timeout = null)
        {
            if (PollMany(sockets, items, pollEvents, out error, timeout))
            {

                if (PollManyResult(sockets, items, pollEvents, ref messages))
                {

                    return true;
                }

                error = ZError.EAGAIN;
            }
            return false;
        }
Beispiel #48
0
			public void SendToBroker(string command, string option, ZMessage msg)
			{
				using (msg = msg != null ? msg.Duplicate() : new ZMessage())
				{
					if (!string.IsNullOrEmpty(option))
						msg.Prepend(new ZFrame(option));
					msg.Prepend(new ZFrame(command));
					msg.Prepend(new ZFrame(MdpCommon.MDPW_WORKER));
					msg.Prepend(new ZFrame(string.Empty));

					if (Verbose)
						msg.DumpZmsg("I: sending '{0:X}|{0}' to broker", command.ToMdCmd());

					Worker.Send(msg);
				}
			}
        public void Send(Type type, byte[] message, Dictionary<string, string> headers = null)
        {
            IList<string> endPoints = _queueMappings[type.FullName];

            foreach (string endPoint in endPoints)
            {
                Dictionary<string, object> messageHeaders = GetHeaders(type, headers, endPoint, "Send");
                var serializedHeaders = JsonConvert.SerializeObject(messageHeaders);

                var msg = new ZMessage();
                msg.Append(new ZFrame(serializedHeaders));
                msg.Append(new ZFrame(message));

                // Send
                _sender.SendMessage(msg);
            }
        }
Beispiel #50
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);
					}
				}
			}
		}
		/// <summary>
		/// Forwards requests from the frontend socket to the backend socket.
		/// </summary>
		protected override bool FrontendHandler(ZSocket sock, out ZMessage message, out ZError error)
		{
			error = default(ZError);
			message = null;

			// receiving scope
			// STREAM: get 2 frames, identity and body
			ZMessage incoming = null;
			// IPAddress address = null;
			string address;
			if (!ReceiveMsg(sock, ref incoming, out address, out error))
			{
				return false;
			}

			// sending scope
			// DEALER: forward
			using (incoming)
			{
				if (incoming[1].Length == 0)
				{
					return true; // Ignore the Empty one
				}

				// Prepend empty delimiter between Identity frame and Data frame
				incoming.Insert(1, new ZFrame());

				// Prepend Peer-Address
				incoming.Insert(2, new ZFrame(address));

				if (!BackendSocket.Send(incoming, /* ZSocketFlags.DontWait, */ out error))
				{
					return false;
				}
				incoming.Dismiss();
			}

			return true;
		}
Beispiel #52
0
        /// <summary>
        /// Forwards replies from the backend socket to the frontend socket.
        /// </summary>
        protected override bool BackendHandler(ZSocket sock, out ZMessage message, out ZError error)
        {
            error = default(ZError);
            message = null;

            // receiving scope
            // DEALER: normal movemsg
            ZMessage incoming = null;
            if (!sock.ReceiveMessage(ref incoming, /* ZSocketFlags.DontWait */ ZSocketFlags.None, out error))
            {
                return false;
            }

            using (incoming)
            {
                // STREAM: write frames: identity, body, identity, empty
                // Read identity
                int ic = (int)incoming[0].Length;
                var identityBytes = new byte[ic];
                incoming[0].Read(identityBytes, 0, ic);

                // Remove DEALER's delimiter
                incoming.RemoveAt(1);

                // Append Identity frame
                var identity0 = new ZFrame(identityBytes);
                incoming.Add(identity0);

                // Append STREAM's empty delimiter frame
                incoming.Add(new ZFrame());

                if (!SendMsg(FrontendSocket, incoming, out error))
                {
                    return false;
                }
            }

            return true;
        }
Beispiel #53
0
		static void Console_WriteZMessage(string format, int messagesNotToRead, ZMessage message, params object[] data)
		{
			var renderer = new StringBuilder();

			var list = new List<object>(data);

			for (int i = messagesNotToRead, c = message.Count; i < c; ++i)
			{
				// here the renderer
				if (i == messagesNotToRead)
				{
					renderer.Append(format);
					renderer.Append(": ");
				}
				else
				{
					renderer.Append(", ");
				}
				renderer.Append("{");
				renderer.Append( (i - messagesNotToRead) + data.Length );
				renderer.Append("}");

				// now the message
				ZFrame frame = message[i];

				frame.Position = 0;

				if (frame.Length == 0)
					list.Add("0");
				else
					list.Add(frame.ReadString());

				frame.Position = 0;
			}

			Console.WriteLine(renderer.ToString(), list.ToArray());
		}
		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);
				}
			}
		}
		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;
				}
			}
		}
		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;
		}
Beispiel #57
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);
			}
		}
		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);
			}
		}
Beispiel #59
0
            //  .split worker send method
            //  This method formats and sends a command to a worker. The caller may
            //  also provide a command option, and a message payload:
            public void Send(string command, string option, ZMessage msg)
            {
                msg = msg != null
                        ? msg.Duplicate()
                        : new ZMessage();

                // Stack protocol envelope to start of message
                if (!string.IsNullOrEmpty(option))
                    msg.Prepend(new ZFrame(option));
                msg.Prepend(new ZFrame(command));
                msg.Prepend(new ZFrame(MdpCommon.MDPW_WORKER));

                // Stack routing envelope to start of message
                msg.Wrap(Identity.Duplicate());

                if(Broker.Verbose)
                    msg.DumpZmsg("I: sending '{0:X}|{0}' to worker", command.ToMdCmd());

                Broker.Socket.Send(msg);
            }
Beispiel #60
0
            //  .split service dispatch method
            //  This method sends requests to waiting workers:
            public void Dispatch(ZMessage msg)
            {
                if (msg != null) // queue msg if any
                    Requests.Add(msg);

                Broker.Purge();
                while (Waiting.Count > 0
                       && Requests.Count > 0)
                {
                    Worker worker = Waiting[0];
                    Waiting.RemoveAt(0);
                    Broker.Waiting.Remove(worker);
                    ZMessage reqMsg = Requests[0];
                    Requests.RemoveAt(0);
                    using (reqMsg)
                        worker.Send(MdpCommon.MdpwCmd.REQUEST.ToHexString(), null, reqMsg);
                }
            }