Beispiel #1
0
        public void SubscriberString(List <string> topics = null)
        {
            SubscriberSocket subscriber = Create(addrPoint);

            Register(subscriber, topics);
            Task.Factory.StartNew(() =>
            {
                try
                {
                    while (true)
                    {
                        string messageTopicReceived = subscriber.ReceiveFrameString();
                        string strReceived          = subscriber.ReceiveFrameString();
                        if (MyFuncOfFlag.IsEndOfFlag(strReceived))
                        {
                            break;
                        }
                        Notify(messageTopicReceived, strReceived);
                    }
                }
                catch { }
                finally
                {
                    Unregister(subscriber, topics);
                }
            });
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            //if (args.Length != 1 || !allowableCommandLineArgs.Contains(args[0]))
            //{
            //    Console.WriteLine("Expected one argument, either " +
            //                      "'TopicA', 'TopicB' or 'All'");
            //    Environment.Exit(-1);
            //}

            //string topic = args[0] == "All" ? "" : args[0];
            string topic = "";

            Console.WriteLine("Subscriber started for Topic : {0}", topic);

            using (var subSocket = new SubscriberSocket())
            {
                subSocket.Options.ReceiveHighWatermark = 1000;
                subSocket.Connect("tcp://localhost:12345");
                subSocket.Subscribe(topic);
                Console.WriteLine("Subscriber socket connecting...");
                while (true)
                {
                    string messageTopicReceived = subSocket.ReceiveFrameString();
                    string messageReceived      = subSocket.ReceiveFrameString();
                    Console.WriteLine(messageReceived);
                    Console.WriteLine("Task delay");
                    Task.Delay(5000).Wait();
                }
            }
        }
        void subskrybuj(string temat, ref bool subskrypcja, ProgressBar pb, TrescWiadomosci tw, Label l)
        {
            using (SubscriberSocket ss = new SubscriberSocket())
            {
                try
                {
                    ss.Connect("tcp://" + poleNaIp.Text + ":12345");
                }
                catch (SocketException se)
                {
                    MessageBox.Show(se.Message);
                    Invoke(new MethodInvoker(() =>
                    {
                        subskrybujGrupa.Enabled        = true;
                        poleNaIp.Enabled               = true;
                        polacz.Enabled                 = true;
                        stop.Enabled                   = false;
                        zarzadzajSerweremGrupa.Enabled = false;
                    }));
                    return;
                }

                ss.Subscribe(temat);
                while (subskrypcja)
                {
                    ss.ReceiveFrameString();
                    float         wartosc = float.Parse(ss.ReceiveFrameString(), CultureInfo.CurrentCulture.NumberFormat);
                    MethodInvoker mi      = new MethodInvoker(() => aktualizujPasekPostepu(pb, wartosc, tw, l));
                    Invoke(mi);
                }
            }
        }
Beispiel #4
0
        private void Consume()
        {
            while (true)
            {
                bool more;
                var  msgType = sub.ReceiveFrameString(out more);
                if (!more)
                {
                    // error
                    break;
                }

                var msg = sub.ReceiveFrameString(out more);
                if (more)
                {
                    // error
                    break;
                }

                var type = Type.GetType(msgType);
                if (type == null)
                {
                    //error
                    break;
                }

                var message = (T)JsonMapper.To(type, msg);
                for (var i = 0; i < pipe.Count; i++)
                {
                    var h = pipe[i];
                    h(message);
                }
            }
        }
Beispiel #5
0
        private void StartReceivingMessages()
        {
            _cancellation = new CancellationTokenSource();
            Task.Run(() =>
            {
                while (!_cancellation.IsCancellationRequested)
                {
                    try
                    {
                        var topic         = _socket.ReceiveFrameString();
                        var messageString = _socket.ReceiveFrameString();

                        var message = Message.Parse(messageString);

                        foreach (var @delegate in MessageReceived?.GetInvocationList().ToArray() ?? new Delegate[0])
                        {
                            ((Action <Message>)@delegate)?.BeginInvoke(message, null, null); // Do not wait while message will be handled
                        }
                    }
                    catch (Exception ex) when(ex is ObjectDisposedException || ex is SocketException)
                    {
                        // Ignore this one: _socket may be closed while waiting the message and this is fine
                    }
                    catch (Exception ex)
                    {
                        // TODO: Log Exception
                        Console.WriteLine("Error while receiving the message: " + ex);
                    }
                }
            }, _cancellation.Token);
        }
        public void TwoPublishers()
        {
            using (var pub = new PublisherSocket())
                using (var pub2 = new PublisherSocket())
                    using (var sub = new SubscriberSocket())
                    {
                        pub.Connect("pgm://224.0.0.1:5555");
                        pub2.Connect("pgm://224.0.0.1:5555");
                        sub.Bind("pgm://224.0.0.1:5555");

                        sub.Subscribe("");

                        pub.SendFrame("Hi");

                        bool more;

                        Assert.AreEqual("Hi", sub.ReceiveFrameString(out more));
                        Assert.IsFalse(more);

                        pub2.SendFrame("Hi2");

                        Assert.AreEqual("Hi2", sub.ReceiveFrameString(out more));
                        Assert.IsFalse(more);
                    }
        }
Beispiel #7
0
        public void Execute()
        {
            using (var jobServerValidationBackend = new PublisherSocket(PUBLISHER))
                using (var jobServerFrontend = new SubscriberSocket(JOB_SERVER_FRONTEND_ENDPOINT))
                {
                    jobServerFrontend.Subscribe("init");

                    Console.WriteLine("Job server ONNNNNNNNNNNNNNNNNN");
                    Console.WriteLine($"Publisher running on: {PUBLISHER}");
                    Console.WriteLine($"Listening to: {JOB_SERVER_FRONTEND_ENDPOINT}");

                    while (true)
                    {
                        try
                        {
                            var topic             = jobServerFrontend.ReceiveFrameString();
                            var event_job_message = jobServerFrontend.ReceiveFrameString();
                            var envelope          = Newtonsoft.Json.JsonConvert.DeserializeObject <Envelope>(event_job_message);

                            Console.WriteLine($"Receive: {envelope.Identity}");

                            jobServerValidationBackend.SendMoreFrame("validation").SendFrame(event_job_message);
                        }
                        catch (Exception ex) //Drop message
                        {
                            Console.WriteLine("Erro na validação do dado: " + ex.Message);
                        }
                    }
                }
        }
Beispiel #8
0
    protected override void Run()
    {
        ForceDotNet.Force(); // this line is needed to prevent unity freeze after one use, not sure why yet

        Debug.Log("Subscriber started");
        using (var subSocket = new SubscriberSocket())
        {
            //subSocket.Options.ReceiveHighWatermark = 1000;
            subSocket.Connect("tcp://127.0.0.1:5555");
            subSocket.Subscribe("22");
            Console.WriteLine("Subscriber socket connecting...");
            while (Running)
            {
                string messageTopicReceived = subSocket.ReceiveFrameString();
                string messageReceived      = subSocket.ReceiveFrameString();
                //Debug.Log(messageReceived);
                carFrontX = Convert.ToSingle(messageReceived.Split(' ')[1]) / 100;
                carFrontZ = Convert.ToSingle(messageReceived.Split(' ')[2]) / 100;
                carBackX  = Convert.ToSingle(messageReceived.Split(' ')[3]) / 100;
                carBackZ  = Convert.ToSingle(messageReceived.Split(' ')[4]) / 100;

                //Debug.Log(carFrontX.ToString() + ":" + carFrontZ.ToString() + " " +carBackX.ToString() + ":" + carBackZ.ToString());
            }
        }
        NetMQConfig.Cleanup(); // this line is needed to prevent unity freeze after one use, not sure why yet
    }
Beispiel #9
0
        /// <summary>
        /// 三经典模式:发布订阅
        /// 消息可以被每个订阅者消费
        /// </summary>
        static void PubSub(string[] args)
        {
            IList <string> allowableCommandLineArgs = new[] { "TopicA", "TopicB", "All" };
            var            a1 = $"{address}:5556";
            var            a2 = $"{address}:5557";

            if (args.Length != 1 || !allowableCommandLineArgs.Contains(args[0]))
            {
                Console.WriteLine("Expected one argument, either " +
                                  "'TopicA', 'TopicB' or 'All'");
                Environment.Exit(-1);
            }
            string topic = args[0] == "All" ? "" : args[0];

            Console.WriteLine("Subscriber started for Topic : {0}", topic);
            using (var subSocket = new SubscriberSocket())
            {
                subSocket.Options.ReceiveHighWatermark = 1000;
                subSocket.Connect(a1);
                subSocket.Subscribe(topic);
                Console.WriteLine("Subscriber socket connecting...");
                while (true)
                {
                    string messageTopicReceived = subSocket.ReceiveFrameString();
                    string messageReceived      = subSocket.ReceiveFrameString();
                    Console.WriteLine(messageReceived);
                }
            }
        }
Beispiel #10
0
        public PriceTickerScreenViewModel()
        {
            // get UI context so can ensure updates are on correct threada
            var uiContext = SynchronizationContext.Current;

            // add the list of Assets to display
            AssetViewModels.Add(new AssetViewModel {
                Name = "Stock 1", Price = 0
            });
            AssetViewModels.Add(new AssetViewModel {
                Name = "Stock 2", Price = 0
            });

            // set up subscriber to asset stream subject
            _assetStream.Subscribe(asset =>
            {
                var avm = AssetViewModels.Single(a => a.Name == asset.Name);

                // update on UI context
                uiContext.Send(_ =>
                {
                    avm.Price = asset.Price;
                    avm.History.Add(new HistoryItem
                    {
                        Timestamp = asset.Timestamp,
                        Price     = asset.Price
                    });
                }, null);
            });

            // connect to the price server, receive updates and push to the subject stream
            Task.Run(() =>
            {
                using (var client = new SubscriberSocket())
                {
                    client.Options.ReceiveHighWatermark = 1000;
                    client.Connect("tcp://localhost:5555");
                    client.Subscribe("Stock 1");
                    client.Subscribe("Stock 2");

                    while (true)
                    {
                        var topicMessage = client.ReceiveFrameString();
                        var message      = client.ReceiveFrameString();

                        // push onto subject
                        _assetStream.OnNext(message.Deserialise <Asset>());
                    }
                }
            });
        }
Beispiel #11
0
 private static void ReceiveFrameString()
 {
     while (true)
     {
         string messageTopicReceived = subscriberSocket.ReceiveFrameString();
         string messageReceived      = subscriberSocket.ReceiveFrameString();
         Console.WriteLine($"{messageReceived}\n");
         //var messages = JsonConvert.DeserializeObject<List<MessageInfo>>(messageReceived);
         //foreach (var message in messages)
         //{
         //    DistributeMessage(message);
         //}
     }
 }
Beispiel #12
0
        static void Main(string[] args)
        {
            using (var sub = new SubscriberSocket())
            {
                sub.Connect("tcp://127.0.0.1:5556");
                sub.Subscribe("A");

                while (true)
                {
                    var topic = sub.ReceiveFrameString();
                    var msg   = sub.ReceiveFrameString();
                    Console.WriteLine($"From publisher: {topic} {msg}");
                }
            }
        }
Beispiel #13
0
        private static void Subscriber()
        {
            using (var subscriber = new SubscriberSocket())
            {
                subscriber.Connect("tcp://127.0.0.1:5556");
                subscriber.Subscribe("");

                while (true)
                {
                    var topic = subscriber.ReceiveFrameString();
                    var msg   = subscriber.ReceiveFrameString();
                    Console.WriteLine("From Publisher: {0} {1}", topic, msg);
                }
            }
        }
Beispiel #14
0
        public void UseInterface()
        {
#if NETCOREAPP1_0
            var hostEntry = Dns.GetHostEntryAsync(Dns.GetHostName()).Result;
#else
            var hostEntry = Dns.GetHostEntry(Dns.GetHostName());
#endif

            string ip = hostEntry.AddressList
                        .Where(addr => addr.AddressFamily == AddressFamily.InterNetwork)
                        .Select(addr => addr.ToString())
                        .FirstOrDefault();

            using (var pub = new PublisherSocket())
                using (var sub = new SubscriberSocket())
                {
                    pub.Connect($"pgm://{ip};224.0.0.1:5555");
                    sub.Bind($"pgm://{ip};224.0.0.1:5555");

                    sub.Subscribe("");

                    pub.SendFrame("Hi");

                    bool more;
                    Assert.AreEqual("Hi", sub.ReceiveFrameString(out more));
                    Assert.IsFalse(more);
                }
        }
Beispiel #15
0
        static void Main(string[] args)
        {
            string topic = "";

            if (args.Length > 0)
            {
                topic = args[0];
            }

            Console.WriteLine($"Initialized Client for numbers that start with {topic}");

            using (var subscriber = new SubscriberSocket())
            {
                subscriber.Connect("tcp://localhost:5555");

                subscriber.Subscribe(topic);

                Console.Write("Received:");
                while (true)
                {
                    var message = subscriber.ReceiveFrameString();

                    Console.Write($" {message}");
                }
            }
        }
Beispiel #16
0
        static void Main(string[] args)
        {
            string endpoint1 = "tcp://127.0.0.1:5556";
            string endpoint2 = "tcp://127.0.0.1:5557";

            try
            {
                using (var socket2 = new SubscriberSocket())
                    using (var socket1 = new SubscriberSocket())
                    {
                        socket1.Connect(endpoint1);
                        socket1.Subscribe("");
                        Console.WriteLine($"Subscriber NetMQ. Binding on {endpoint1}");

                        socket2.Connect(endpoint2);
                        socket2.Subscribe("");
                        Console.WriteLine($"Subscriber NetMQ. Binding on {endpoint2}");


                        while (true)
                        {
                            string messageTopicReceived1 = socket1.ReceiveFrameString();
                            string messageTopicReceived2 = socket2.ReceiveFrameString();

                            Console.WriteLine(messageTopicReceived2);
                            Console.WriteLine(messageTopicReceived1);
                        }
                    }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Beispiel #17
0
 void Run()
 {
     while (_running)
     {
         try
         {
             string topic;
             if (_subSocket.TryReceiveFrameString(TimeSpan.FromMilliseconds(100), out topic))
             {
                 var eventName       = _subSocket.ReceiveFrameString();
                 var messageReceived = _subSocket.ReceiveFrameBytes();
                 try
                 {
                     MessaggioRicevuto(eventName, messageReceived);
                 }
                 catch
                 {
                 }
             }
         }
         catch (Exception ex)
         {
             if (_running)
             {
                 Console.WriteLine(this.GetType().Name + " : " + ex.Message);
             }
         }
     }
 }
Beispiel #18
0
        /// <summary>
        ///     Subscription worker
        ///     - Creates ZMQ subscriber socket and listens for specified frames
        /// </summary>
        private void SubscribeWorker()
        {
            using (var subscriber = new SubscriberSocket())
            {
                subscriber.Connect(_zmqConnectTo);
                subscriber.Subscribe(_zmqSubscribeTopic);
                Console.WriteLine("Subscribed to ZeroMQ '" + _zmqConnectTo + "' publisher for '" + _zmqSubscribeTopic + "' frames.");

                while (true)
                {
                    // we expect the publisher to sends 3 frames per data packet
                    // first, the header frame
                    var replyHeader = subscriber.ReceiveFrameString();
                    if (replyHeader != _zmqSubscribeTopic)
                    {
                        Console.WriteLine("Unexpected Frame Header! '" + _zmqSubscribeTopic + "' expected, but received " + replyHeader +
                                          ". Skipping and waiting for proper frame header.");
                        continue;
                    }

                    // next, the data frame
                    var replyFrame = subscriber.ReceiveFrameBytes();

                    // last, the reply counter frame
                    var replyCounter = BitConverter.ToInt32(subscriber.ReceiveFrameBytes(), 0);
                    // Console.WriteLine("counter: " + replyCounter);

                    // pass the received data to our consumer thread
                    _consumer.EnqueueTask(replyFrame, replyCounter);
                }
            }
        }
Beispiel #19
0
        static void Main(string[] args)
        {
            using (var pubSocket = new PublisherSocket())

            {
                using (var subSocket = new SubscriberSocket())
                {
                    pubSocket.Bind("tcp://127.0.0.1:55555");

                    var msg = new BlockedOrderCreated();

                    //  pubSocket.SendMoreFrame("BlockedOrderTopic").SendFrame(msg.content);

                    Thread.Sleep(500);

                    subSocket.Connect("tcp://127.0.0.1:55555");
                    Thread.Sleep(500);
                    subSocket.Subscribe("BlockedOrderTopic");
                    pubSocket.SendMoreFrame("BlockedOrderTopic").SendFrame(msg.content);
                    while (true)
                    {
                        Thread.Sleep(500);
                        var messageReceived = subSocket.ReceiveFrameString();
                        Thread.Sleep(500);
                        Debug.WriteLine(messageReceived);
                    }
                }
            }
        }
Beispiel #20
0
        /// <summary>
        ///     Subscription worker
        ///     - Creates ZMQ subscriber socket and listens for specified frames
        /// </summary>
        private void SubscribeWorker()
        {
            using (var subscriber = new SubscriberSocket())
            {
                subscriber.Connect(_connectTo.AbsoluteUri.TrimEnd('/'));
                subscriber.Subscribe(_subscribeTopic);
                Console.WriteLine("Subscribed to ZeroMQ '" + _connectTo + "' publisher for '" + _subscribeTopic + "' frames.");

                while (true)
                {
                    // the publisher sends 3 frames per data packet
                    // first, the header frame
                    var replyHeader = subscriber.ReceiveFrameString();
                    // if this is not a valid header frame, continue to next frame
                    if (replyHeader != _subscribeTopic)
                    {
                        Console.WriteLine("Unexpected Frame Header! '" + _subscribeTopic + "' expected, but received " + replyHeader +
                                          ". Skipping and waiting for proper frame header.");
                        continue;
                    }

                    // next, the data frame
                    var replyFrame = subscriber.ReceiveFrameBytes();

                    // last, the reply counter frame
                    var replyCounter = BitConverter.ToInt32(subscriber.ReceiveFrameBytes(), 0);

                    // pass the received data to callback function
                    _callback(replyHeader, replyFrame, replyCounter);
                }
            }
        }
Beispiel #21
0
        static void Main(string[] args)
        {
            var zipcode = new Random().Next(0, 10);

            Console.WriteLine($"接收本地天气预报{zipcode}……");

            OnReceiveMsg += Program_OnReceiveMsg;

            using (var subscriber = new SubscriberSocket())
            {
                subscriber.Connect("tcp://127.0.0.1:8888");

                subscriber.Subscribe(zipcode.ToString(CultureInfo.InvariantCulture)); // 设置过滤字符串
                //subscriber.Subscribe(""); // 订阅所有的发布端内容

                while (true)
                {
                    string recMsg = subscriber.ReceiveFrameString(Encoding.UTF8);
                    Console.WriteLine(".");

                    var msgs = recMsg.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    if (int.Parse(msgs[0]) == zipcode)
                    {
                        OnReceiveMsg(recMsg);
                    }
                }
            }
        }
Beispiel #22
0
        /*
         * this function create the pubsub connection with the server.
         * The function sends the messages to the correct window
         */
        private void PUBSUB()
        {
            Console.WriteLine("Subscriber started for Topic : {0}", "General");

            using (var subSocket = new SubscriberSocket())
            {
                subSocket.Options.ReceiveHighWatermark = 1000; //for checking
                subSocket.Connect("tcp://localhost:12346");    // 12346- port
                subSocket.Subscribe("General");                // listen to topic name
                Console.WriteLine("Subscriber socket connecting...");

                while (!exit)
                {
                    string messageReceived = subSocket.ReceiveFrameString();
                    try
                    {
                        dynamic recived = DeserializeServerMsg(messageReceived);
                        if (recived != null)
                        {
                            Message.Invoke(this, recived);// event that create changes in the form
                        }
                    }
                    catch (ThreadAbortException)
                    {
                        throw;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
            }
        }
Beispiel #23
0
        public static void Main(string[] args)
        {
            const int MegaBit  = 1024;
            const int MegaByte = 1024;

            using (var pub = new PublisherSocket())
                using (var sub1 = new SubscriberSocket())
                    using (var sub2 = new SubscriberSocket())
                    {
                        pub.Options.MulticastHops             = 2;
                        pub.Options.MulticastRate             = 40 * MegaBit; // 40 megabit
                        pub.Options.MulticastRecoveryInterval = TimeSpan.FromMinutes(10);
                        pub.Options.SendBuffer = MegaByte * 10;               // 10 megabyte
                        pub.Connect("pgm://224.0.0.1:5555");
                        sub1.Options.ReceiveBuffer = MegaByte * 10;
                        sub1.Bind("pgm://224.0.0.1:5555");
                        sub1.Subscribe("");
                        sub2.Bind("pgm://224.0.0.1:5555");
                        sub2.Options.ReceiveBuffer = MegaByte * 10;
                        sub2.Subscribe("");
                        Console.WriteLine("Server sending 'Hi'");
                        pub.SendFrame("Hi", false);
                        bool more;
                        Console.WriteLine("sub1 received = '{0}'", sub1.ReceiveFrameString(out more));
                        Console.WriteLine("sub2 received = '{0}'", sub2.ReceiveFrameString(out more));
                    }
        }
Beispiel #24
0
        public void SetPgmSettings()
        {
            const int MegaBit  = 1024;
            const int MegaByte = 1024;

            using (var pub = new PublisherSocket())
                using (var sub = new SubscriberSocket())
                {
                    pub.Options.MulticastHops             = 2;
                    pub.Options.MulticastRate             = 40 * MegaBit; // 40 megabit
                    pub.Options.MulticastRecoveryInterval = TimeSpan.FromMinutes(10);
                    pub.Options.SendBuffer = MegaByte * 10;               // 10 megabyte

                    pub.Connect("pgm://224.0.0.1:5555");

                    sub.Options.ReceiveBuffer = MegaByte * 10;
                    sub.Bind("pgm://224.0.0.1:5555");

                    sub.Subscribe("");

                    pub.SendFrame("Hi");

                    bool more;
                    Assert.AreEqual("Hi", sub.ReceiveFrameString(out more));
                    Assert.IsFalse(more);

                    Assert.AreEqual(2, pub.Options.MulticastHops);
                    Assert.AreEqual(40 * MegaBit, pub.Options.MulticastRate);
                    Assert.AreEqual(TimeSpan.FromMinutes(10), pub.Options.MulticastRecoveryInterval);
                    Assert.AreEqual(MegaByte * 10, pub.Options.SendBuffer);
                    Assert.AreEqual(MegaByte * 10, sub.Options.ReceiveBuffer);
                }
        }
Beispiel #25
0
 private void Subscribe(string topic)
 {
     using (var subSocket = new SubscriberSocket())
     {
         subSocket.Options.ReceiveHighWatermark = 1000;
         subSocket.Connect("tcp://localhost:12345");
         subSocket.Subscribe(topic);
         Console.WriteLine("Subscriber socket connecting...");
         while (true)
         {
             string messageTopicReceived = subSocket.ReceiveFrameString();
             string messageReceived      = subSocket.ReceiveFrameString();
             Console.WriteLine(messageReceived);
         }
     }
 }
        private void FilteredBackgroundWorker(object sender, DoWorkEventArgs e)
        {
            var filter = (string)e.Argument;

            using (var subscriberSocket = new SubscriberSocket())
            {
                subscriberSocket.Options.ReceiveHighWatermark = 1000;
                subscriberSocket.Connect(transportMethod + "eventsystem");
                subscriberSocket.Subscribe(filter);
                while (!e.Cancel)
                {
                    string messageTopicReceived = subscriberSocket.ReceiveFrameString();
                    byte[] message      = subscriberSocket.ReceiveFrameBytes();
                    var    eventMessage = EventMessage.Create(message);

                    Debug.Log("Event received for " + filter + "|" + messageTopicReceived);

                    foreach (var actionDelegate in subscriberDelegates[filter])
                    {
                        try
                        {
                            actionDelegate.Invoke(eventMessage.Sender, eventMessage.Parameter);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }
            }
        }
Beispiel #27
0
 /*
  * this function create the pubsub connection with the server.
  * The function sends the messages to the correct window
  *** we call this function after the user connect to new call.
  */
 private void createPubSubConnection(string _topic)
 {
     using (var subSocket = new SubscriberSocket())
     {
         subSocket.Options.ReceiveHighWatermark = 1000;
         subSocket.Connect("tcp://localhost:12346");
         subSocket.Subscribe(_topic);
         while (!exit)
         {
             string messageReceived = subSocket.ReceiveFrameString();
             try
             {
                 dynamic recived = DeserializeServerMsg(messageReceived);
                 if (recived != null)
                 {
                     Message.Invoke(this, recived);// event that create changes in the form
                 }
             }
             catch (ThreadAbortException)
             {
                 throw;
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex);
             }
         }
     }
 }
        private void HandleNextConsumer()
        {
            using (_consumerSocket = new SubscriberSocket())
            {
                _consumerSocket.Options.ReceiveHighWatermark = 1000;
                _consumerSocket.Connect(_currentProducer.Endpoint);
                _consumerSocket.Subscribe(_consumerConfiguration.Topic);

                while (!_cancel.IsCancellationRequested && !_currentConsumerTaskCancellation.IsCancellationRequested)
                {
                    var topic            = _consumerSocket.ReceiveFrameString();
                    var messageBytes     = _consumerSocket.ReceiveFrameBytes();
                    var transportMessage = JsonConvert.DeserializeObject <TransportMessage>(Encoding.UTF32.GetString(messageBytes));

                    if (transportMessage.MessageType != typeof(TEvent))
                    {
                        throw new InvalidOperationException($"wrong event type {transportMessage.MessageType} vs expected {typeof(TEvent)}");
                    }

                    var message = (TEvent)JsonConvert.DeserializeObject(Encoding.UTF32.GetString(transportMessage.Message), transportMessage.MessageType);

                    _subject.OnNext(message);
                }
            }
        }
Beispiel #29
0
        private void Run()
        {
            while (isRunning)
            {
                try
                {
                    bool hasMore;
                    var  clientIdString = subscribeSocket.ReceiveFrameString(out hasMore);

                    if (hasMore)
                    {
                        var receiedBuffer = subscribeSocket.ReceiveFrameBytes(out hasMore);

                        if (!hasMore && receiedBuffer != null && receiedBuffer.Length > 0)
                        {
                            var deserialized = serializer.Deserialize <ServerToClientMessage>(receiedBuffer);
                            if (deserialized != null && messageHandler != null)
                            {
                                messageHandler(deserialized);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }
Beispiel #30
0
    protected override void Run()
    {
        AsyncIO.ForceDotNet.Force(); // this line is needed to prevent unity freeze after one use, not sure why yet

        using (SUB = new SubscriberSocket())
            using (PUB = new PublisherSocket())
                using (REQ = new RequestSocket()) {
                    SUB.Connect("tcp://localhost:5555");
                    SUB.Subscribe("");

                    PUB.Connect("tcp://localhost:5556");

                    REQ.Connect("tcp://localhost:5557");

                    Debug.Log("Connected: Receiving Messages");

                    while (Running)
                    {
                        /*Receive continuos Slicer data*/
                        string msg = SUB.ReceiveFrameString();

                        /*Send continuos Unity data*/
                        var bytes = new byte[dataPackage.t.Length * 4];
                        System.Buffer.BlockCopy(dataPackage.t, 0, bytes, 0, bytes.Length);
                        PUB.SendFrame(bytes);

                        /*Request volume data once*/
                        if (reqestData)
                        {
                            REQ.SendFrame("volume");
                            string msg2 = REQ.ReceiveFrameString();
                            Debug.Log(msg2);

                            byte[] file = System.IO.File.ReadAllBytes(msg2);
                            Debug.Log(file.Length);

                            int     d1     = System.BitConverter.ToInt32(file, 0);
                            int     d2     = System.BitConverter.ToInt32(file, 4);
                            int     d3     = System.BitConverter.ToInt32(file, 8);
                            float[] volume = new float[d1 * d2 * d3];
                            System.Buffer.BlockCopy(file, 12, volume, 0, volume.Length * sizeof(float));

                            string s = d1 + " " + d2 + " " + d3 + " : ";
                            //for (int i = 0; i < volume.Length; ++i) s += volume[i] + " ";
                            Debug.Log(s);

                            reqestData = false;
                        }

                        /*60fps*/
                        System.Threading.Thread.Sleep(16);
                    }

                    SUB.Close();
                    PUB.Close();
                    REQ.Close();
                }
        NetMQConfig.Cleanup();
    }
Beispiel #31
0
 static void Main(string[] args)
 {
     using (var subSocket = new SubscriberSocket())
     {
         subSocket.Options.ReceiveHighWatermark = 100;
         subSocket.Connect("tcp://localhost:12345");
         subSocket.Subscribe("");
         Console.WriteLine("Subscriber socket connecting...");
         while (true)
         {
             string messageTopicReceived = subSocket.ReceiveFrameString();
             string messageReceived = subSocket.ReceiveFrameString();
             Console.WriteLine(messageReceived);
             Thread.Sleep(300);
         }
     }
 }
Beispiel #32
0
        private static void Main()
        {
            Console.Title = "NetMQ Weather Update Client";

            const int zipToSubscribeTo = 10001;
            const int iterations = 100;

            int totalTemp = 0;
            int totalHumidity = 0;

            Console.WriteLine("Collecting updates for weather service for zipcode {0}...", zipToSubscribeTo);

            using (var subscriber = new SubscriberSocket())
            {
                subscriber.Connect("tcp://127.0.0.1:5556");
                subscriber.Subscribe(zipToSubscribeTo.ToString(CultureInfo.InvariantCulture));

                for (int i = 0; i < iterations; i++)
                {
                    string results = subscriber.ReceiveFrameString();
                    Console.Write(".");

                    // "zip temp relh" ... "10001 84 23" -> ["10001", "84", "23"]
                    string[] split = results.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    int zip = int.Parse(split[0]);
                    if (zip != zipToSubscribeTo)
                    {
                        throw new Exception(string.Format("Received message for unexpected zipcode: {0} (expected {1})", zip, zipToSubscribeTo));
                    }

                    totalTemp += int.Parse(split[1]);
                    totalHumidity += int.Parse(split[2]);
                }
            }

            Console.WriteLine();
            Console.WriteLine("Average temperature was: {0}", totalTemp/iterations);
            Console.WriteLine("Average relative humidity was: {0}", totalHumidity/iterations);
        }
Beispiel #33
0
        private static void SubscriberContinuousLoop(string pubSubAddress, string requestString)
        {
            Task.Factory.StartNew(() =>
            {
                using (var progressSubscriber = new SubscriberSocket())
                {
                    progressSubscriber.Connect(pubSubAddress);
                    progressSubscriber.SubscribeToAnyTopic();
                    while (true)
                    {
                        var topic = progressSubscriber.ReceiveFrameString();
                        RequestSocket.ProgressTopic progressTopic;
                        Enum.TryParse(topic, out progressTopic);
                        switch (progressTopic)
                        {
                            case RequestSocket.ProgressTopic.Send:
                                Console.WriteLine("C: Sending {0}", requestString);
                                break;
                            case RequestSocket.ProgressTopic.Retry:
                                Console.WriteLine("C: No response from server, retrying...");
                                break;
                            case RequestSocket.ProgressTopic.Failure:
                                Console.WriteLine("C: Server seems to be offline, abandoning");
                                break;
                            case RequestSocket.ProgressTopic.Success:
                                Console.WriteLine("C: Server replied OK");
                                break;
                            default:
                                throw new ArgumentOutOfRangeException();
                        }


                    }
                }
            });
        }