Exemplo n.º 1
0
        private static void XSubscriberSocket()
        {
            using var subSocket = new SubscriberSocket();
            string loginMark = "";
            string userName  = "";

            subSocket.Connect(_subscriberAddress);
            subSocket.Subscribe($"{_topic}/{TopicType.EquipAddEvent}");
            subSocket.Subscribe($"{_topic}/{TopicType.EquipChangeEvent}");
            subSocket.Subscribe($"{_topic}/{TopicType.EquipDeleteEvent}");
            subSocket.Subscribe($"{_topic}/{TopicType.YcChangeEvent}/{11151}");
            subSocket.Subscribe($"{_topic}/{TopicType.YxChangeEvent}/{11151}");
            subSocket.Subscribe($"{_topic}/{TopicType.SendControl}/{11151}");
            subSocket.Subscribe($"{_topic}/{TopicType.AddRealTimeSnapshot}");
            subSocket.Subscribe($"{_topic}/{TopicType.EquipStateEvent}");
            subSocket.Subscribe($"{_topic}/{TopicType.DeleteRealTimeSnapshot}");
            subSocket.Subscribe($"{_topic}/{TopicType.OpenPage4InterScreen}");
            subSocket.Subscribe($"{_topic}/{TopicType.ShowOrClosePage}");
            subSocket.Subscribe($"{_topic}/{TopicType.KickClient}/{loginMark}");
            subSocket.Subscribe($"{_topic}/{TopicType.ShowMsg}");
            subSocket.Subscribe($"{_topic}/{TopicType.NotifyOffLine}");
            subSocket.Subscribe($"{_topic}/{TopicType.NotifyRoleOffLine}");
            subSocket.Subscribe($"{_topic}/{TopicType.ShowLockSetParmMsg}");
            subSocket.Subscribe($"{_topic}/{TopicType.VOpenPage}/{userName}");
            subSocket.Subscribe($"{_topic}/{TopicType.ShowInfo}");
            subSocket.SubscribeToAnyTopic();
            Console.WriteLine("Subscriber socket connecting...\n");
            ReceiveFrameString();
        }
Exemplo n.º 2
0
        private void Run()
        {
            using var publisher = new PublisherSocket();

            publisher.Bind(@"tcp://127.0.0.1:17232");

            using var subscriber = new SubscriberSocket();
            subscriber.Bind(@"tcp://127.0.0.1:17233");
            subscriber.SubscribeToAnyTopic();

            running.Set();

            using var server = new TelnetServer(IPAddress.Any, port, publisher, subscriber)
                  {
                      OptionReuseAddress = true
                  };

            Log.Information("Server starting ...");

            server.Start();

            while (running.WaitOne(TimeSpan.Zero))
            {
                if (subscriber.TryReceiveFrameBytes(TimeSpan.FromMilliseconds(100), out var frame))
                {
                    server.Multicast(frame);
                }
            }

            server.Stop();

            Log.Information("Server stopped.");
        }
Exemplo n.º 3
0
        public async Task ListenToEddn()
        {
            var utf8 = new UTF8Encoding();

            using (var client = new SubscriberSocket())
            {
                client.Options.ReceiveHighWatermark = 1000;
                client.Connect("tcp://eddn.edcd.io:9500");
                client.SubscribeToAnyTopic();
                while (true)
                {
                    var bytes        = client.ReceiveFrameBytes();
                    var uncompressed = ZlibStream.UncompressBuffer(bytes);

                    var result = utf8.GetString(uncompressed);

                    // ignore all outfitting and commodity responses
                    if (!result.Contains(@"""Influence"""))
                    {
                        continue;
                    }

                    Submissions.Add(EddnRequest.FromJson(result));
                }
            }
        }
Exemplo n.º 4
0
        public void RequestResponseMultipartMessageWithRetryFails()
        {
            const string address        = "tcp://127.0.0.1:50002";
            const string pubAddress     = "tcp://127.0.0.1:60002";
            const int    numTries       = 5;
            var          requestTimeout = TimeSpan.FromMilliseconds(100);
            var          requestMessage = new NetMQMessage(1);

            requestMessage.Append("Hi");

            using (var progressPublisher = new PublisherSocket(pubAddress))
                using (var progressSubscriber = new SubscriberSocket(pubAddress))
                    using (var server = new RouterSocket(address))
                    {
                        progressSubscriber.SubscribeToAnyTopic();
                        var progressProactor = new NetMQProactor(progressSubscriber, (socket, message) =>
                                                                 Console.WriteLine("C: {0} {1:ss.fff}", message[0].ConvertToString(), DateTime.Now));

                        var serverProactor = new NetMQProactor(server, (socket, message) =>
                        {
                            Console.WriteLine("ResponseEcho recieved message {0} at {1:ss.fff}", message[2].ConvertToString(),
                                              DateTime.Now);
                        });

                        using (serverProactor)
                            using (progressProactor)
                            {
                                var responseMessage = RequestSocket.RequestResponseMultipartMessageWithRetry(address, requestMessage,
                                                                                                             numTries, requestTimeout, progressPublisher);
                                Assert.IsNull(responseMessage);
                            }
                    }
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            var utf8 = new UTF8Encoding();

            try
            {
                using (var client = new SubscriberSocket())
                {
                    client.Options.ReceiveHighWatermark = 1000;
                    client.Connect("tcp://eddn.edcd.io:9500");
                    client.SubscribeToAnyTopic();
                    while (true)
                    {
                        var bytes        = client.ReceiveFrameBytes();
                        var uncompressed = ZlibStream.UncompressBuffer(bytes);

                        var result = utf8.GetString(uncompressed);

                        addmessage(result);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.Read();
            }
        }
Exemplo n.º 6
0
        public void Run()
        {
            try
            {
                while (true)
                {
                    using (SubscriberSocket sock = new SubscriberSocket())
                    {
                        sock.Connect("tcp://eddn-relay.elite-markets.net:9500");
                        sock.SubscribeToAnyTopic();

                        Msg msg = new Msg();
                        msg.InitEmpty();

                        while (sock.TryReceive(ref msg, TimeSpan.FromMinutes(10)))
                        {
                            Process(msg);
                            msg.Close();
                            msg.InitEmpty();
                        }
                    }
                }
            }
            finally
            {
                NetMQConfig.Cleanup();
            }
        }
Exemplo n.º 7
0
        private async Task ClientAsync()
        {
            var utf8 = new UTF8Encoding();

            using (var client = new SubscriberSocket())
            {
                client.Connect(_eddnClientSettings.ConnectionString);
                client.SubscribeToAnyTopic();
                while (true)
                {
                    try
                    {
                        (var bytes, _) = await client.ReceiveFrameBytesAsync();

                        var uncompressed = ZlibStream.UncompressBuffer(bytes);
                        var result       = utf8.GetString(uncompressed);
                        await _messageDistributor.DistributeAsync(result);

                        _logger.LogInformation(result);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "Error reading message queue");
                    }
                }
            }
        }
Exemplo n.º 8
0
        private void HandleWork()
        {
            using (var stateUpdate = new SubscriberSocket())
            {
                stateUpdate.SubscribeToAnyTopic();
                stateUpdate.Bind(_configuration.ToPublisherEndpoint);

                using (var stateUpdatePublish = new PublisherSocket())
                {
                    stateUpdatePublish.Bind(_configuration.ToSubscribersEndpoint);

                    stateUpdate.ReceiveReady += async(s, e) =>
                    {
                        var message = e.Socket.ReceiveMultipartMessage();

                        var subject = message[0].ConvertToString();
                        var payload = message[1];

                        var eventId = await _cache.AppendToStream(subject, payload.Buffer);

                        stateUpdatePublish.SendMoreFrame(message[0].Buffer)
                        .SendMoreFrame(_serializer.Serialize(eventId))
                        .SendFrame(payload.Buffer);
                    };

                    using (_poller = new NetMQPoller {
                        stateUpdate, stateUpdatePublish
                    })
                    {
                        _poller.Run();
                    }
                }
            }
        }
Exemplo n.º 9
0
        private void StartStationNetMQ()
        {
            try
            {
                _subscriber = new SubscriberSocket();
                _subscriber.ReceiveReady += _subscriber_ReceiveReady;
                //_fileSubscriber = new SubscriberSocket();
                _requester = new RequestSocket();
                _poller    = new NetMQPoller();

                IsLocalClient = CheckIsLocalIP(this.Options.ServerAddress);

                _subscriber.Connect(string.Format("tcp://{0}:{1}", this.Options.ServerAddress, this.Options.MsgPubPort));
                _subscriber.SubscribeToAnyTopic();
                _requester.Connect(string.Format("tcp://{0}:{1}", this.Options.ServerAddress, this.Options.MsgResPort));
                //_fileSubscriber.Connect(string.Format("tcp://{0}:{1}", this.Options.ServerAddress, this.Options.FilePubPort));
                //_fileSubscriber.SubscribeToAnyTopic();

                logger.InfoFormat("peripheral client netmq info: IP-{0},msg pub port:{1},msg res port:{2}", this.Options.ServerAddress, this.Options.MsgPubPort, this.Options.MsgResPort);

                // HockSocketEvents(true);

                //_poller.Add(_fileSubscriber);
                _poller.Add(_subscriber);
                _poller.Add(_requester);

                _poller.RunAsync();
                Console.WriteLine("[Progress]:[4] Sub Listening");

                // this.OnConnected();
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 10
0
        private void ThreadSub()
        {
            List <SubscriberSocket> socklist = new List <SubscriberSocket>();
            var sock = new SubscriberSocket();

            sock.Options.IPv4Only = true;
            sock.SubscribeToAnyTopic();

            foreach (var port in PortList)
            {
                string addr = $"tcp://{IPAddress.Loopback}:{port}";
                sock.Connect(addr);
            }

            Thread.Sleep(2000);

            while (EventStop.Wait(WaitInterval) == false)
            {
                var    buffer = sock.ReceiveFrameBytes();
                string msg    = Encoding.Unicode.GetString(buffer);
                textBox1.AppendLine(msg);
            }

            sock.Close();
        }
Exemplo n.º 11
0
        public ZeroMqNotificationReader Init()
        {
            if (Initialized)
            {
                throw new InvalidOperationException($"{nameof(ZeroMqNotificationReader)} already initialized.");
            }

            var completionSource = new TaskCompletionSource <object>();
            var token            = _source.Token;

            _receiveTask = Task.Factory.StartNew(() =>
            {
                var timeout = TimeSpan.FromSeconds(1);

                using (var subSocket = new SubscriberSocket(EndPoint))
                {
                    try
                    {
                        subSocket.Options.ReceiveHighWatermark = 1000;
                        subSocket.SubscribeToAnyTopic();

                        while (!token.IsCancellationRequested)
                        {
                            var zMessage        = new NetMQMessage(2);
                            var messageReceived = subSocket.TryReceiveMultipartMessage(timeout, ref zMessage, 2);
                            completionSource.TrySetResult(null);

                            if (!messageReceived)
                            {
                                continue;
                            }

                            var topic = zMessage.Pop().ConvertToString(Encoding.UTF8);
                            var json  = zMessage.Pop().ConvertToString(Encoding.UTF8);

                            OnNotificationReceived?.Invoke(topic, json);
                        }
                    }
                    catch (Exception e)
                    {
                        OnError?.Invoke(e);
                    }
                }
            }, TaskCreationOptions.LongRunning);

            _receiveTask.ContinueWith(t =>
            {
                // Propagate exception from initialization if occured
                if (t.Exception != null)
                {
                    completionSource.TrySetException(t.Exception);
                }
            });

            completionSource.Task.GetAwaiter().GetResult();

            Initialized = true;
            return(this);
        }
Exemplo n.º 12
0
    // Start is called before the first frame update
    private void Start()
    {
        _hip = GetComponent <Rigidbody>();

        _pub.Bind(pubAddress);

        _sub.Connect(subAddress);
        _sub.SubscribeToAnyTopic();
        _sub.Options.ReceiveHighWatermark = 1;
    }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            //TestSerilog();

            using (var subSocket = new SubscriberSocket())
            {
                var tcpLocalhost = "tcp://localhost:12345";
                subSocket.Connect(tcpLocalhost);
                subSocket.SubscribeToAnyTopic();
                Console.WriteLine("Waiting to Connect");

                var connectMessage = subSocket.ReceiveMultipartMessage();
                if (connectMessage[0].ConvertToString(Encoding.UTF8) == "CONNECT")
                {
                    Console.WriteLine("Connected");

                    var port = connectMessage[1].ConvertToString(Encoding.UTF8);
                    using (var reqSocket = new RequestSocket(port))
                    {
                        var syncMessage = new NetMQMessage();
                        syncMessage.Append(new NetMQFrame("SYNC", Encoding.UTF8));
                        syncMessage.Append(new NetMQFrame(tcpLocalhost, Encoding.UTF8));
                        reqSocket.SendMultipartMessage(syncMessage);
                        Console.WriteLine("Syncing");
                        var syncOk = reqSocket.ReceiveFrameString();
                        Console.WriteLine($"Synced: {syncOk}");
                    }

                    using (var poller = new NetMQPoller())
                    {
                        poller.Add(subSocket);

                        subSocket.ReceiveReady += (sender, eventArgs) =>
                        {
                            var subMessage = eventArgs.Socket.ReceiveMultipartMessage();
                            var topic      = subMessage[0].ConvertToString(Encoding.UTF8);
                            if (topic == "TopicA")
                            {
                                var decodedMessage = MessagePackSerializer.Deserialize <string>(subMessage[1].ToByteArray());
                                Console.WriteLine(
                                    $"{subMessage[0].ConvertToString(Encoding.UTF8)}: {decodedMessage}");
                            }
                        };

                        poller.RunAsync();

                        Console.WriteLine("Press Enter to Exit");
                        Console.ReadLine();

                        poller.StopAsync();
                    }
                }
            }
        }
Exemplo n.º 14
0
 private void Register(SubscriberSocket subscriber, List <string> topics = null)
 {
     if (topics == null)
     {
         subscriber.SubscribeToAnyTopic();
     }
     else
     {
         topics.ForEach(item => subscriber.Subscribe(item));
         timeout.Add(subscriber, DateTime.Now);
     }
 }
Exemplo n.º 15
0
        private void InitSub()
        {
            subscriber = new SubscriberSocket();
            subscriber.Connect(Address);
            subscriber.ReceiveReady += _Subscire_ReceiveReady;
            subscriber.SubscribeToAnyTopic();

            subscriberPoller = new NetMQPoller {
                subscriber
            };
            subscriberPoller.RunAsync();
        }
Exemplo n.º 16
0
        private void Subscribe()
        {
            subscribing = true;

            subscriberSocket.Connect(@"tcp://127.0.0.1:17232");
            subscriberSocket.SubscribeToAnyTopic();

            while (subscribing)
            {
                if (subscriberSocket.TryReceiveFrameBytes(TimeSpan.FromMilliseconds(100), out var frame))
                {
                    teleprinter.Read(frame[^ 1]);
Exemplo n.º 17
0
        public void ConnectSubscribe()
        {
            subscriber = new SubscriberSocket();
            subscriber.Connect(SubscribeAddress);
            subscriber.ReceiveReady += _Subscire_ReceiveReady;
            subscriber.SubscribeToAnyTopic();

            subscriberPoller = new NetMQPoller {
                subscriber
            };
            subscriberPoller.RunAsync();
        }
Exemplo n.º 18
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _subscriberSocket.Connect(_options.Address);
            _subscriberSocket.SubscribeToAnyTopic();
            while (true)
            {
                var bytesReceived = _subscriberSocket.ReceiveFrameBytes();
                var uncompressed  = ZlibStream.UncompressBuffer(bytesReceived);
                var entity        = _encoding.GetString(uncompressed);
                await _importTargetFactory.ImportAsync(entity);

                _logger.LogInformation(entity);
            }
        }
Exemplo n.º 19
0
        private static void Main(string[] args)
        {
            var deciSecond = new TimeSpan(10000);

            using (var subscriber = new SubscriberSocket()) // For receiving updates from presentation host
                using (var publisher = new WSPublisher())   // For publishing updates from presentation host to audience
                    using (var responder = new WSRouter())  // Handling on-demand requests for late-joining or crashing clients
                    {
                        subscriber.Bind("tcp://*:3000");
                        subscriber.SubscribeToAnyTopic();
                        publisher.Bind("ws://*:3001");
                        responder.Bind("ws://*:3002");

                        byte step = 0;
                        subscriber.ReceiveReady += (_, __) => {
                            if (!subscriber.TryReceiveFrameBytes(deciSecond, out var received))
                            {
                                return;
                            }
                            step = received[0];
                            Console.Out.WriteLine("Sending " + step + " to audience.");
                            publisher.TrySendFrame(deciSecond, new[] { step });
                        };
                        responder.ReceiveReady += (_, __) => {
                            NetMQMessage msg = null;
                            if (!responder.TryReceiveMultipartMessage(deciSecond, ref msg))
                            {
                                return;
                            }
                            var identity = msg.Pop().Buffer;
                            var request  = msg.Pop().ConvertToString();
                            msg.Clear();
                            if (request == "Which slide are we on?")
                            {
                                responder.TrySendMultipartBytes(deciSecond, identity, new[] { step });
                            }
                            else
                            {
                                if (!responder.TrySendFrame(deciSecond, identity, true))
                                {
                                    return;
                                }
                                responder.TrySendFrameEmpty(deciSecond);
                            }
                        };
                        new NetMQPoller {
                            subscriber, responder
                        }.Run();                               // Polling both subscriber and router sockets.
                    }
        }
Exemplo n.º 20
0
        public void Start()
        {
            _publishStateUpdate = new PublisherSocket();
            _publishStateUpdate.Bind(_brokerConfiguration.PublishUpdatesEndpoint);

            _subscribeToUpdates = new SubscriberSocket();
            _subscribeToUpdates.SubscribeToAnyTopic();
            _subscribeToUpdates.Bind(_brokerConfiguration.SubscribeToUpdatesEndpoint);

            _stateRequest = new RouterSocket();
            _stateRequest.Bind(_brokerConfiguration.SendStateEndpoint);

            _workProc       = Task.Run(DoStart, _cancel.Token).ConfigureAwait(false);
            _heartBeartProc = Task.Run(HandleHeartbeat, _cancel.Token).ConfigureAwait(false);
        }
Exemplo n.º 21
0
        private void SubscribeThread()
        {
            // Place subscribe socket initialization inside thread to make all subscribe calls happen on the same thread
            // Trying to prevent "Cannot close an uninitialised Msg" exceptions
            _subscribeSocket = new SubscriberSocket();
            _subscribeSocket.Connect(_subscribeAddress);
            _subscribeSocket.SubscribeToAnyTopic();

            _subscribeThreadRunning = true;

            while (!_subscribeThreadCancellation.IsCancellationRequested)
            {
                try
                {
                    if (!_subscribeSocket.TryReceiveFrameBytes(new TimeSpan(0, 0, 0, 0, 200), out byte[] messageBytes))
Exemplo n.º 22
0
        public void ThreadB()
        {
            try
            {
                using (var subSocket = new SubscriberSocket())
                {
                    subSocket.Options.ReceiveHighWatermark = 1000;
                    FillIP   = ConfigurationManager.AppSettings["FillIP"];
                    FillPort = ConfigurationManager.AppSettings["FillPort"];
                    subSocket.Connect("tcp://" + FillIP + ":" + FillPort);

                    subSocket.SubscribeToAnyTopic();
                    //subSocket.Subscribe(OrderClient.MachineGuid + ":" + OrderClient.UserGuid);

                    //Console.WriteLine("Subscriber socket connecting...");
                    while (true)
                    {
                        try
                        {
                            if (ScannerBox.openedMainForm == false)
                            {
                                break;
                            }
                            string messageReceived;
                            if (subSocket.TryReceiveFrameString(out messageReceived))
                            {
                                //string messageReceived = subSocket.ReceiveFrameString();
                                Console.WriteLine("messageReceived " + messageReceived);
                                string[] arr = messageReceived.Split(':');
                                //machineID + ":" + userID+":"+OrderNo+":"+ExchangeOrderId+":"+status+":"+status_msg+":"+other_msg
                                //[3d0e9dfa-5c5d-85a2-1833-e1e1cf52c13e:b5479e69-9bab-1023-068f-f8bafaafb7de:35:1470420475:0:0:0
                                //machineID + ":" + userID + ":" + OrderNo + ":" + OrderStatus + ":" + ExchangeOrderId + ":" + status + ":" + status_msg + ":" + other_msg;
                                dictFillDetails[arr[2]] = arr[3] + ":" + arr[4] + ":" + arr[5] + ":" + arr[6] + ":" + arr[7];
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("fillsubscriber : " + e.Message);
                        }
                        System.Threading.Thread.Sleep(100);
                    }
                }
            }
            finally
            {
                NetMQConfig.Cleanup();
            }
        }
        private void HandleWork()
        {
            using (var stateUpdate = new SubscriberSocket())
            {
                stateUpdate.SubscribeToAnyTopic();
                stateUpdate.Bind(_configuration.ToPublisherEndpoint);

                stateUpdate.Options.ReceiveHighWatermark = _configuration.ZmqHighWatermark;

                using (var stateUpdatePublish = new PublisherSocket())
                {
                    stateUpdatePublish.Bind(_configuration.ToSubscribersEndpoint);

                    stateUpdate.ReceiveReady += async(s, e) =>
                    {
                        try
                        {
                            NetMQMessage message = null;

                            while (e.Socket.TryReceiveMultipartMessage(ref message))
                            {
                                var subject = message[0];
                                var payload = message[1];

                                stateUpdatePublish.SendMoreFrame(subject.Buffer)
                                .SendMoreFrame(_serializer.Serialize(await _cache.AppendToStream(subject.Buffer, payload.Buffer)))
                                .SendFrame(payload.Buffer);
                            }
                        }
                        catch (Exception ex)
                        {
                            Errors.Add(new ActorMonitoringError()
                            {
                                CacheErrorStatus = ActorErrorType.DynamicCacheEventHandlingFailure,
                                Exception        = ex
                            });
                        }
                    };

                    using (_workPoller = new NetMQPoller {
                        stateUpdate, stateUpdatePublish
                    })
                    {
                        _workPoller.Run();
                    }
                }
            }
        }
        private void ConnectServer(string subAddress)
        {
            _subscriber = new SubscriberSocket();
            _subscriber.SubscribeToAnyTopic();
            _subscriber.Connect(subAddress);
            _subscriber.ReceiveReady += _subscriber_ReceiveReady;

            _poller = new NetMQPoller {
                _subscriber
            };

            _poller.RunAsync();
            Thread.Sleep(1000);
            //如果改变参数 2台client 会收不到信息
            //this._beacon.SelfNode.Arguments = string.Format("-c {0}", this.IsConnected);
        }
Exemplo n.º 25
0
        private async Task ConnectToBroker()
        {
            _cancel = new CancellationTokenSource();

            _getMarketState = new DealerSocket();
            _getMarketState.Connect(_currentBroker.GetStateEndpoint);
            _getMarketState.Options.Identity = Id.ToByteArray();

            _getMarketUpdates = new SubscriberSocket();
            _getMarketUpdates.SubscribeToAnyTopic();
            _getMarketUpdates.Connect(_currentBroker.SubscribeToUpdatesEndpoint);

            _heartbeatProc = Task.Run(() => DoHeartbeat(_configuration.HearbeatDelay, _configuration.HearbeatMaxDelay), _cancel.Token).ConfigureAwait(false);
            _workProc      = Task.Run(ReceiveUpdates, _cancel.Token).ConfigureAwait(false);

            await Synchronize();
        }
 /// <summary>
 /// Creates a new instance of the <see cref="DualSocketBusSubscriber"/> type.
 /// </summary>
 /// <param name="messageBusEndpoint"> The subscribed message bus' endpoint. </param>
 /// <param name="dispatcher"> The dispatcher that is used for incoming messages from the subscibed bus. </param>
 /// <param name="scheduler">
 /// An optional scheduler that can be used to deserialize incoming <see cref="NetMQMessage"/> instances on a separate thread.
 /// </param>
 protected DualSocketBusSubscriber(
     IDualSocketEndpoint messageBusEndpoint,
     ISocketDispatcherThread dispatcher,
     IScheduler?scheduler = null)
 {
     Dispatcher         = dispatcher;
     MessageBusEndpoint = messageBusEndpoint;
     IncomingMessages   = new Lazy <SubscriberSocket>(() =>
     {
         var incomingMessages = new SubscriberSocket();
         incomingMessages.SubscribeToAnyTopic();
         incomingMessages.Connect(MessageBusEndpoint.Outgoing);
         incomingMessages.ReceiveReady += OnIncomingMessageReceived;
         return(incomingMessages);
     }, true);
     Scheduler = scheduler;
 }
Exemplo n.º 27
0
        public void RequestResponseMultipartMessageWithRetrySucceedsNotOnFirstTry()
        {
            const string address        = "tcp://127.0.0.1:50001";
            const string pubAddress     = "tcp://127.0.0.1:60001";
            const int    numTries       = 5;
            var          requestTimeout = TimeSpan.FromMilliseconds(100);
            var          requestMessage = new NetMQMessage(1);

            requestMessage.Append("Hi");

            using (var progressPublisher = new PublisherSocket(pubAddress))
                using (var progressSubscriber = new SubscriberSocket(pubAddress))
                    using (var server = new RouterSocket(address))
                    {
                        progressSubscriber.SubscribeToAnyTopic();
                        var progressProactor = new NetMQProactor(progressSubscriber, (socket, message) =>
                                                                 Console.WriteLine("C: {0} {1:ss.fff}", message[0].ConvertToString(), DateTime.Now));

                        int attempt = 0;

                        var serverProactor = new NetMQProactor(server, (socket, message) =>
                        {
                            Console.WriteLine("ResponseEcho recieved message {0} at {1:ss.fff}", message[2].ConvertToString(),
                                              DateTime.Now);

                            attempt++;

                            if (attempt > 1)
                            {
                                // reply same message
                                socket.SendMultipartMessage(message);
                            }
                        });

                        using (serverProactor)
                            using (progressProactor)
                            {
                                var responseMessage = RequestSocket.RequestResponseMultipartMessageWithRetry(address,
                                                                                                             requestMessage, numTries, requestTimeout, progressPublisher);
                                Assert.IsNotNull(responseMessage);
                                Assert.AreEqual(1, responseMessage.FrameCount);
                                var responseString = responseMessage.First.ConvertToString();
                                Assert.AreEqual("Hi", responseString);
                            }
                    }
        }
Exemplo n.º 28
0
        private void Work()
        {
            using (var subscriberSocket = new SubscriberSocket())
            {
                subscriberSocket.Options.ReceiveHighWatermark = 1000;
                subscriberSocket.SubscribeToAnyTopic();
                subscriberSocket.Connect(_toPublisherEndpoint);


                using (var publisherSocket = new XPublisherSocket())
                {
                    publisherSocket.Options.XPubVerbose = true;
                    publisherSocket.Bind(_toSubscribersEndpoint);

                    using (_poller = new NetMQPoller {
                        new NetMQTimer(TimeSpan.FromMilliseconds(1)), subscriberSocket, publisherSocket
                    })
                    {
                        subscriberSocket.ReceiveReady += (s, e) =>
                        {
                            var message = e.Socket.ReceiveMultipartBytes();
                            var topic   = Encoding.UTF8.GetString(message[0]);
                            var payload = message[1];

                            _cache[topic] = payload;

                            publisherSocket.SendMultipartBytes(message);
                        };

                        publisherSocket.ReceiveReady += (s, e) =>
                        {
                            var message = e.Socket.ReceiveFrameBytes();
                            var isSub   = message[0] == 1;
                            var topic   = Encoding.UTF8.GetString(message.Skip(1).ToArray());

                            if (_cache.ContainsKey(topic))
                            {
                                publisherSocket.SendMoreFrame(Encoding.UTF8.GetBytes(topic)).SendFrame(_cache[topic]);
                            }
                        };

                        _poller.Run();
                    }
                }
            }
        }
Exemplo n.º 29
0
        public Receiver(string sFile = "")
        {
            if (sFile.Equals("") == false)
            {
                sLogfile = sFile;
            }

            subscriber = new SubscriberSocket();

            subscriber.Connect(sEndpoint);

            subscriber.SubscribeToAnyTopic();

            file = new System.IO.StreamWriter(sLogfile);

            file.AutoFlush = true;
        }
Exemplo n.º 30
0
        /// <summary>
        /// Starts the local to external message transfering.
        /// </summary>
        /// <param name="proxyForPublishersPort">The port for local publishers.</param>
        /// <param name="busPublisherPort">Broker's publisher port for other brokers subscription.</param>
        private void StartLocalToExternalTransfer(int proxyForPublishersPort, int busPublisherPort)
        {
            Task.Run(() =>
            {
                using (var subSocket = new SubscriberSocket())
                    using (var pubSocket = new PublisherSocket())
                    {
                        subSocket.SubscribeToAnyTopic();
                        subSocket.Bind($"tcp://localhost:{proxyForPublishersPort}");

                        pubSocket.Bind($"tcp://localhost:{busPublisherPort}");

                        _localToExternalProxy = new NetMQ.Proxy(subSocket, pubSocket);

                        _localToExternalProxy.Start();
                    }
            });
        }