Beispiel #1
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 #2
0
        public async Task <XtResult <TMessage> > PublishAsync <TMessage>(TMessage message)
            where TMessage : class, new()
        {
            PublisherSocket publisherSocket = null;

            try
            {
                publisherSocket = new PublisherSocket();
                publisherSocket.Connect(_configuration.Address());
                return(await Task.Run(() =>
                {
                    try
                    {
                        var msg = new PubSubMessage <TMessage>(_configuration, message);
                        publisherSocket.SendMultipartMessage(msg);
                    }
                    catch (System.Exception ex)
                    {
                        return XtResult <TMessage> .Failed(ex, "publish");
                    }

                    return XtResult <TMessage> .Success(message, "publish");
                }));
            }
            catch (System.Exception ex)
            {
                return(XtResult <TMessage> .Failed(ex, "publish"));
            }
            finally
            {
                publisherSocket?.Dispose();
            }
        }
Beispiel #3
0
        public void Start()
        {
            _messageHost?.Start();

            lock (_publishSocketLocker)
            {
                _publishSocket = new PublisherSocket();
                _publishSocket.Connect(_publishAddress);
            }

            _subscribeThreadCancellation = new CancellationTokenSource();
            _pingThreadCancellation      = new CancellationTokenSource();

            _subscribeThread = new Thread(SubscribeThread)
            {
                IsBackground = true
            };
            _subscribeThread.Start();

            _pingThread = new Thread(PingThread)
            {
                IsBackground = true
            };
            _pingThread.Start();

            // Wait until the subscribe thread has actually subscribed before continuing.
            // For some reason a "reset event" doesn't work here.
            while (!_subscribeThreadRunning)
            {
                Thread.Sleep(50);
            }
        }
Beispiel #4
0
 public ActorPublisher()
 {
     actor_id = random_string(5);
     var context = NetMQContext.Create();
     pub = context.CreatePublisherSocket();
     pub.Connect("tcp://localhost:5012");
 }
Beispiel #5
0
        private void TaskDataPub(CancellationToken cancelToken, BlockingCollection <object> queue, string address)
        {
            using (var pubSocket = new PublisherSocket())
            {
                //pubSocket.Options.SendHighWatermark = 1;
                pubSocket.Connect(address);

                while (!cancelToken.IsCancellationRequested)
                {
                    if (queue.TryTake(out object data, 500))
                    {
                        switch (data.GetType().Name)
                        {
                        case "ClientHeartbeat":
                            pubSocket.Serialise <ClientHeartbeat>(data);
                            break;

                        case "ClientPositionUpdate":
                            pubSocket.Serialise <ClientPositionUpdate>(data);
                            break;

                        case "ClientFrequencyUpdate":
                            pubSocket.Serialise <ClientFrequencyUpdate>(data);
                            break;
                        }
                    }
                }
            }
            taskDataPub = null;
        }
        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 #7
0
    // Client thread which does not block Update()
    void NetMQClient()
    {
        AsyncIO.ForceDotNet.Force();
        NetMQConfig.ManualTerminationTakeOver();
        NetMQConfig.ContextCreate(true);

        //string msg;
        var timeout = new System.TimeSpan(0, 0, 1); //1sec

        Debug.Log("Connect to the server.");

        pubSocket = new PublisherSocket();
        pubSocket.Options.ReceiveHighWatermark = 0;
        pubSocket.Connect("tcp://192.168.1.122:55556");

        bool is_connected = true;

        while (is_connected && stop_thread_ == false)
        {
            pubSocket.TrySendFrame(timeout, final);
        }

        pubSocket.Close();
        Debug.Log("ContextTerminate.");
        NetMQConfig.ContextTerminate();
        NetMQConfig.Cleanup();
    }
Beispiel #8
0
        private void OnBeaconReady(object sender, NetMQBeaconEventArgs e)
        {
            var readyTime = DateTimeOffset.Now;

            var message = _beacon.Receive();

            int.TryParse(message.String, out var port);

            var peer = new PeerInfo(message.PeerHost, port);

            if (!_info.ContainsKey(peer))
            {
                _info.Add(peer, readyTime);
                _publisher.Connect(peer.Address);
                _shim.SendMoreFrame("A").SendFrame(peer.Address);

                _logger?.LogInformation($"{_id}: Added new peer from '{{PeerAddress}}'", peer.Address);
                _hub?.Clients.All.SendAsync("ReceiveMessage", "success", $"Adding new peer from '{peer.Address}'");
            }
            else
            {
                _logger?.LogDebug($"{_id}: Updating keep-alive for peer '{{PeerAddress}}'", peer.Address);
                _info[peer] = readyTime;
            }
        }
Beispiel #9
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 #10
0
        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 #11
0
        public virtual NetMQSocket Rent()
        {
            if (_pool.TryDequeue(out var _sender))
            {
                Interlocked.Decrement(ref _count);

                Debug.Assert(_count >= 0);
                return(_sender);
            }

            try
            {
                switch (_options.Pattern)
                {
                case NetMQPattern.PushPull:
                    _sender = new PushSocket();
                    break;

                case NetMQPattern.PubSub:
                    _sender = new PublisherSocket();
                    break;

                default:
                    break;
                }
                _sender.Connect(HostAddress);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "ZeroMQ channel model create failed!");
                throw;
            }

            return(_sender);
        }
        private void mq_test()
        {
            mq_end   = true;
            time_cnt = 0;
            try
            {
                using (var publisher = new PublisherSocket())
                {
                    publisher.Connect("tcp://127.0.0.1:5550");
                    while (mq_end)
                    {
                        int x = (int)(100 * Math.Sin(time_cnt));
                        int y = 0;//(int)obj1;
                        this.chkPx.Location = new System.Drawing.Point(x + 150, 257 + y);

                        byte[][] bytes = { Encoding.ASCII.GetBytes("foo"), Encoding.ASCII.GetBytes($"{x}") };

                        publisher.SendMultipartBytes(bytes);
                        time_cnt += 0.05;

                        Thread.Sleep(10);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Beispiel #13
0
        public void LargeMessage()
        {
            using (var pub = new PublisherSocket())
                using (var sub = new SubscriberSocket())
                {
                    pub.Connect("pgm://224.0.0.1:5555");
                    sub.Bind("pgm://224.0.0.1:5555");

                    sub.Subscribe("");

                    var data = new byte[3200]; // this should be at least 3 packets

                    for (Int16 i = 0; i < 1600; i++)
                    {
                        Array.Copy(BitConverter.GetBytes(i), 0, data, i * 2, 2);
                    }

                    pub.SendFrame(data);

                    byte[] message = sub.ReceiveFrameBytes();

                    Assert.AreEqual(3200, message.Length);

                    for (Int16 i = 0; i < 1600; i++)
                    {
                        Assert.AreEqual(i, BitConverter.ToInt16(message, i * 2));
                    }
                }
        }
Beispiel #14
0
        private void OnBeaconReady(object sender, NetMQBeaconEventArgs e)
        {
            // we got another beacon
            // let's check if we already know about the beacon
            var message = m_beacon.Receive();
            int port;

            int.TryParse(message.String, out port);

            NodeKey node = new NodeKey(message.PeerHost, port);

            // check if node already exist
            if (!m_nodes.ContainsKey(node))
            {
                // we have a new node, let's add it and connect to subscriber
                m_nodes.Add(node, DateTime.Now);
                m_publisher.Connect(node.Address);
                m_shim.SendMoreFrame(AddedNodeCommand).SendFrame(node.Address);
            }
            else
            {
                //Console.WriteLine("Node {0} is not a new beacon.", node);
                m_nodes[node] = DateTime.Now;
            }
        }
Beispiel #15
0
        /// <summary>
        /// <para>Constructs a publisher socket.</para>
        /// </summary>
        /// <param name="address">Address to which to connect (for example: tcp://localhost:9001).</param>
        /// <param name="context">ZMQ Context.</param>
        /// <param name="verboseLog">Enable tracing of each event published.</param>
        /// <param name="traceWriter">Traces</param>
        internal Publisher(string address, NetMQContext context, bool verboseLog, ITraceWriter traceWriter)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (string.IsNullOrEmpty(address))
            {
                throw new ArgumentNullException("address");
            }
            if (traceWriter == null)
            {
                throw new ArgumentNullException("traceWriter");
            }

            _traces           = traceWriter;
            _verboseLog       = verboseLog;
            _instanceHashCode = this.GetHashCode();

            _socket = context.CreatePublisherSocket();
            _socket.Options.SendHighWatermark = 100000;
            try
            {
                _socket.Connect(address);
                _traces.Debug("Publisher({0:x}) created ({1}).", _instanceHashCode, address);
            }
            catch (Exception ex)
            {
                _traces.Error(ex);
                _socket.Dispose();
                throw;
            }
        }
Beispiel #16
0
        private void OnBeaconReady(object sender, NetMQBeaconEventArgs e)
        {
            // we got another beacon
            // let's check if we already know about the beacon
            string nodeName;
            int    port = Convert.ToInt32(m_beacon.ReceiveString(out nodeName));

            // remove the port from the peer name
            nodeName = nodeName.Replace(":" + m_broadcastPort, "");

            NodeKey node = new NodeKey(nodeName, port);

            // check if node already exist
            if (!m_nodes.ContainsKey(node))
            {
                // we have a new node, let's add it and connect to subscriber
                m_nodes.Add(node, DateTime.Now);
                m_publisher.Connect(node.Address);
                m_shim.SendMoreFrame(AddedNodeCommand).SendFrame(node.Address);
            }
            else
            {
                //Console.WriteLine("Node {0} is not a new beacon.", node);
                m_nodes[node] = DateTime.Now;
            }
        }
Beispiel #17
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();
    }
        protected override Task RunInternal()
        {
            _publisherSocket = new PublisherSocket();
            _publisherSocket.Connect(_configuration.BrokerEndpoint);
            _heartbeatProc = Task.Run(HandleHeartbeat, _cancel.Token);

            return Task.CompletedTask;
        }
 private void createSSocket()
 {
     clientS = context.CreatePublisherSocket();
     string[] srAddrs = cfg.ServerR.Split(',');
     foreach (string addr in srAddrs)
     {
         clientS.Connect(addr);
     }
 }
        protected override Task RunInternal()
        {
            _heartbeatProc = Task.Run(HandleHeartbeat, _cancel.Token).ConfigureAwait(false);

            _publisherSocket = new PublisherSocket();
            _publisherSocket.Connect(_configuration.RouterEndpoint);

            return(Task.CompletedTask);
        }
 /// <summary>
 /// Default ctor.
 /// </summary>
 public FeedMuxMessageBroker()
 {
     context   = NetMQContext.Create();
     pubSocket = context.CreatePublisherSocket();
     pubSocket.Connect(PublisherAddress);
     pollerCancelled = new ManualResetEvent(false);
     source          = new CancellationTokenSource();
     token           = source.Token;
     StartPolling();
 }
Beispiel #22
0
        /// <summary>
        /// Starts the publisher, connecting it to specified subscrubers.
        /// </summary>
        /// <param name="subscribers">The subscribers to connect.</param>
        /// <param name="selfIdentity">The self identity.</param>
        public void Start(List <IPEndPoint> subscribers, PeerIdentity selfIdentity)
        {
            _selfIdentity = selfIdentity;

            _socket = new PublisherSocket();

            foreach (var subscriber in subscribers)
            {
                _socket.Connect($"tcp://{subscriber.Address}:{subscriber.Port}");
            }
        }
Beispiel #23
0
        public void Sending1000Messages()
        {
            // creating two different context and sending 1000 messages

            int count = 0;

            var subReady = new ManualResetEvent(false);

            Task subTask = Task.Factory.StartNew(() =>
            {
                using (var sub = new SubscriberSocket())
                {
                    sub.Bind("pgm://224.0.0.1:5555");
                    sub.Subscribe("");

                    subReady.Set();

                    while (count < 1000)
                    {
                        bool more;
                        Assert.AreEqual(count, BitConverter.ToInt32(sub.ReceiveFrameBytes(out more), 0));
                        Assert.IsFalse(more);
                        count++;
                    }
                }
            });

            subReady.WaitOne();

            Task pubTask = Task.Factory.StartNew(() =>
            {
                using (var pub = new PublisherSocket())
                {
                    pub.Connect("pgm://224.0.0.1:5555");

                    for (int i = 0; i < 1000; i++)
                    {
                        pub.SendFrame(BitConverter.GetBytes(i));
                    }

                    // if we close the socket before the subscriber receives all messages subscriber
                    // might miss messages, lets wait another second
                    Thread.Sleep(1000);
                }
            });

            pubTask.Wait();
            subTask.Wait();

            Thread.MemoryBarrier();

            Assert.AreEqual(1000, count);
        }
Beispiel #24
0
        public void Connect(string givenAddress)
        {
            if (IsConnected)
            {
                return;
            }

            pubSocket = context.CreatePublisherSocket();
            pubSocket.Connect(givenAddress);

            IsConnected = true;
        }
Beispiel #25
0
        static void Main(string[] args)
        {
            //using (var server = new ResponseSocket("@tcp://localhost:5556")) // bind
            //using (var client = new RequestSocket(">tcp://localhost:5556"))  // connect
            //{
            //    // Send a message from the client socket
            //    client.SendFrame("Hello");

            //    // Receive the message from the server socket
            //    string m1 = server.ReceiveFrameString();
            //    Console.WriteLine("From Client: {0}", m1);

            //    // Send a response back from the server
            //    server.SendFrame("Hi Back");

            //    // Receive the response from the client socket
            //    string m2 = client.ReceiveFrameString();
            //    Console.WriteLine("From Server: {0}", m2);
            //}

            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.Send("Hi");

                        bool more;
                        Console.WriteLine("sub1 received = '{0}'", sub1.ReceiveString(out more));
                        Console.WriteLine("sub2 received = '{0}'", sub2.ReceiveString(out more));
                    }


            Console.ReadLine();
        }
Beispiel #26
0
        public void ThroughXPubXSubWithReconnectingPublisher()
        {
            using (var xpub = new XPublisherSocket())
                using (var xsub = new XSubscriberSocket())
                    using (var poller = new NetMQPoller {
                        xsub, xpub
                    })
                    {
                        var xPubPort = (ushort)xpub.BindRandomPort("tcp://*");
                        var xSubPort = (ushort)xsub.BindRandomPort("tcp://*");

                        var proxy = new Proxy(xsub, xpub, poller: poller);
                        proxy.Start();

                        poller.RunAsync();

                        // long running subscriber
                        using (var sub = new SubscriberSocket())
                        {
                            sub.Connect(string.Format("tcp://localhost:{0}", xPubPort));
                            sub.Subscribe("A");

                            // publisher 1
                            using (var pub = new PublisherSocket())
                            {
                                pub.Connect(string.Format("tcp://localhost:{0}", xSubPort));
                                // give the publisher a chance to learn of the subscription
                                Thread.Sleep(100);
                                pub.SendMoreFrame("A").SendFrame("1");
                            }

                            // publisher 2
                            using (var pub = new PublisherSocket())
                            {
                                pub.Connect(string.Format("tcp://localhost:{0}", xSubPort));
                                // give the publisher a chance to learn of the subscription
                                Thread.Sleep(100);
                                pub.SendMoreFrame("A").SendFrame("2");
                            }

                            var frames = new List <string>();

                            Assert.True(sub.TryReceiveMultipartStrings(TimeSpan.FromSeconds(1), ref frames));
                            CollectionAssert.AreEqual(new[] { "A", "1" }, frames);

                            Assert.True(sub.TryReceiveMultipartStrings(TimeSpan.FromSeconds(1), ref frames));
                            CollectionAssert.AreEqual(new[] { "A", "2" }, frames);
                        }
                    }
        }
Beispiel #27
0
        public async Task ShouldHandleStateOfTheWorldRequest()
        {
            using (var publisher = new PublisherSocket())
            {
                publisher.Connect(ToPublishersEndpoint);

                var command1 = new ChangeCcyPairState("EUR/USD", "TEST2", CcyPairState.Passive);
                var command2 = new ChangeCcyPairState("EUR/USD", "TEST2", CcyPairState.Active);

                var message1 = _eventSerializer.ToProducerMessage(command1);
                var message2 = _eventSerializer.ToProducerMessage(command2);

                await Task.Delay(200);

                publisher.SendMoreFrame(message1.Subject)
                .SendFrame(_eventSerializer.Serializer.Serialize(message1));

                await Task.Delay(200);

                publisher.SendMoreFrame(message2.Subject)
                .SendFrame(_eventSerializer.Serializer.Serialize(message2));

                await Task.Delay(200);

                var cacheItems = await _eventCache.GetAllStreams();

                Assert.AreEqual(2, cacheItems.Count());

                using (var dealer = new DealerSocket())
                {
                    var request = new StateRequest()
                    {
                        Subject = "EUR/USD"
                    };

                    var requestBytes = _eventSerializer.Serializer.Serialize(request);

                    dealer.Connect(StateOfTheWorldEndpoint);
                    dealer.SendFrame(requestBytes);

                    var hasResponse = dealer.TryReceiveFrameBytes(TimeSpan.FromMilliseconds(1000), out var responseBytes);

                    var response = _eventSerializer.Serializer.Deserialize <StateReply>(responseBytes);

                    Assert.AreEqual(2, response.Events.Count());
                }
            }
        }
Beispiel #28
0
        private void Publish()
        {
            publishing = true;

            publisherSocket.Connect(@"tcp://127.0.0.1:17233");

            while (publishing)
            {
                if (teleprinter.CachedDataAvailableEvent.WaitOne(TimeSpan.FromMilliseconds(200)))
                {
                    if (!publisherSocket.TrySendFrame(teleprinter.GetCachedOutput()))
                    {
                        Log.Debug("Failed to send frame.");
                    }
                }
            }
        }
        private void Work()
        {
            using (var publisherSocket = new PublisherSocket())
            {
                publisherSocket.Connect(_brokerEndpoint);

                while (!_cancel.IsCancellationRequested)
                {
                    var price = Next();

                    publisherSocket
                    .SendMoreFrame(Topic)
                    .SendFrame(price.Serialize());

                    Thread.Sleep(50);
                }
            }
        }
 /// <summary>
 /// Creates a new instance of the <see cref="DualSocketBusPublisher"/> type.
 /// </summary>
 /// <param name="messageBusEndpoint"> The subscribed message bus' endpoint. </param>
 /// <param name="dispatcher"> The dispatcher that is used for outgoing messages from the subscibed bus. </param>
 public DualSocketBusPublisher(
     IDualSocketEndpoint messageBusEndpoint,
     ISocketDispatcherThread dispatcher)
 {
     Dispatcher         = dispatcher;
     MessageBusEndpoint = messageBusEndpoint;
     OutgoingMessages   = new Lazy <PublisherSocket>(() =>
     {
         var socket = new PublisherSocket();
         socket.Connect(MessageBusEndpoint.Incoming);
         return(socket);
     }, true);
     OutgoingMessageQueue = new Lazy <NetMQQueue <NetMQMessage> >(() =>
     {
         var queue           = new NetMQQueue <NetMQMessage>();
         queue.ReceiveReady += OnMessageQueued;
         return(queue);
     }, true);
 }
Beispiel #31
0
        public async Task Start()
        {
            _publishMarketUpdates = new PublisherSocket();

            foreach (var broker in _configuration.BrokerDescriptors)
            {
                _publishMarketUpdates.Connect(broker.PublishUpdateEndpoint);
            }

            _disconnected = IsConnected
                            .Buffer(2, 1)
                            .Where(buffer => buffer.Count > 1 && buffer[0] && !buffer[1])
                            .Subscribe(async _ =>
            {
                await DoStart();
            });

            await DoStart();
        }
Beispiel #32
0
        private void SenderWorker()
        {
            _mqContext = NetMQContext.Create();
            _publisherSocket = _mqContext.CreatePublisherSocket();

            if (Protocol == "tcp")
                _publisherSocket.Connect(_address);

            if (Protocol == "pgm") //Multicast
            {
                _publisherSocket.Options.MulticastHops = 4;
                _publisherSocket.Options.MulticastRate = 40 * 1024; // 40 megabit
                _publisherSocket.Options.MulticastRecoveryInterval = TimeSpan.FromMinutes(10);
                _publisherSocket.Options.SendBuffer = 1024 * 10; // 10 megabyte
                _publisherSocket.Bind(_address);
            }

            _publisherSocket.SendReady += (s, a) => { };
        }