コード例 #1
0
        /// <summary>
        /// Remote <see cref="IAddress"/> from the socket
        /// </summary>
        /// <param name="address"><see cref="IAddress"/> to be removed</param>
        public override void SocketRemove(IAddress address)
        {
            if (disposedValue)
            {
                throw new InvalidOperationException("NetMQSender has been disposed");
            }

            socket.Disconnect(address.ToString());
        }
コード例 #2
0
ファイル: SocketTests.cs プロジェクト: masaeedu/netmq
        public void Disconnect(string protocol)
        {
            using (var server1 = new DealerSocket())
                using (var server2 = new DealerSocket())
                    using (var client = new DealerSocket())
                    {
                        string address2;

                        if (protocol == "tcp")
                        {
                            var port1 = server1.BindRandomPort("tcp://localhost");
                            var port2 = server2.BindRandomPort("tcp://localhost");

                            client.Connect("tcp://localhost:" + port1);
                            client.Connect("tcp://localhost:" + port2);

                            address2 = "tcp://localhost:" + port2;
                        }
                        else
                        {
                            server1.Bind("inproc://localhost1");
                            server2.Bind("inproc://localhost2");

                            client.Connect("inproc://localhost1");
                            client.Connect("inproc://localhost2");

                            address2 = "inproc://localhost2";
                        }

                        Thread.Sleep(100);

                        // we should be connected to both server
                        client.SendFrame("1");
                        client.SendFrame("2");

                        // make sure client is connected to both servers
                        server1.SkipFrame();
                        server2.SkipFrame();

                        // disconnect from server2, server 1 should receive all messages
                        client.Disconnect(address2);
                        Thread.Sleep(100);

                        client.SendFrame("1");
                        client.SendFrame("2");

                        server1.SkipFrame();
                        server1.SkipFrame();
                    }
        }
コード例 #3
0
        private bool CreateRealTimeRequestSocket()
        {
            realTimeRequestSocket = new DealerSocket(realTimeRequestConnectionString);
            realTimeRequestSocket.Options.Identity = Encoding.UTF8.GetBytes(name);
            // Start off by sending a ping to make sure everything is regular
            byte[] reply = new byte[] { };
            try
            {
                realTimeRequestSocket.SendMoreFrame(string.Empty)
                .SendFrame(BitConverter.GetBytes((byte)DataRequestMessageType.Ping));

                if (realTimeRequestSocket.TryReceiveFrameBytes(TimeSpan.FromSeconds(1), out reply))
                {
                    realTimeRequestSocket.TryReceiveFrameBytes(TimeSpan.FromMilliseconds(50), out reply);
                }
            }
            catch
            {
                Disconnect();
            }

            if (reply?.Length > 0)
            {
                DataRequestMessageType type = (DataRequestMessageType)BitConverter.ToInt16(reply, 0);

                if (type != DataRequestMessageType.Pong)
                {
                    try
                    {
                        realTimeRequestSocket.Disconnect(realTimeRequestConnectionString);
                    }
                    finally
                    {
                        realTimeRequestSocket.Close();
                        realTimeRequestSocket = null;
                    }

                    RaiseEvent(Error, this, new ErrorArgs(-1, "Could not connect to server."));

                    return(true);
                }
            }
            else
            {
                RaiseEvent(Error, this, new ErrorArgs(-1, "Could not connect to server."));
            }

            realTimeRequestSocket.ReceiveReady += RealTimeRequestSocketReceiveReady;
            return(false);
        }
コード例 #4
0
ファイル: EventBus.cs プロジェクト: minamaras/redNimbus
        public void Stop()
        {
            try
            {
                _poller.Stop();
                _publisherSocket.Disconnect(_publisherAddress);
                _dealerSocket.Disconnect(_dealerAddress);

                _poller.Dispose();
                _publisherSocket.Dispose();
                _dealerSocket.Dispose();
            }
            finally
            {
                NetMQConfig.Cleanup();
            }
        }
コード例 #5
0
 private void StopRealTimeRequestSocket()
 {
     lock (realTimeRequestSocketLock)
     {
         if (realTimeRequestSocket != null)
         {
             try
             {
                 realTimeRequestSocket.Disconnect(realTimeRequestConnectionString);
             }
             finally
             {
                 realTimeRequestSocket.ReceiveReady -= RealTimeRequestSocketReceiveReady;
                 realTimeRequestSocket.Close();
                 realTimeRequestSocket = null;
             }
         }
     }
 }
コード例 #6
0
 private void StopHistoricalDataSocket()
 {
     lock (historicalDataSocket)
     {
         if (historicalDataSocket != null)
         {
             try
             {
                 historicalDataSocket.Disconnect(historicalDataConnectionString);
             }
             finally
             {
                 historicalDataSocket.ReceiveReady -= HistoricalDataSocketReceiveReady;
                 historicalDataSocket.Close();
                 historicalDataSocket = null;
             }
         }
     }
 }
コード例 #7
0
ファイル: BaseService.cs プロジェクト: minamaras/redNimbus
        /// <summary>
        /// Shut down the service and clean up resources.
        /// </summary>
        public void Stop()
        {
            if (IsRunning)
            {
                try
                {
                    _poller.Stop();
                    _subscriberSocket.Disconnect(_publisherAddress);
                    _dealerSocket.Disconnect(_dealerAddress);

                    _poller.Dispose();
                    _subscriberSocket.Dispose();
                    _dealerSocket.Dispose();
                }
                finally
                {
                    IsRunning = false;
                    NetMQConfig.Cleanup();
                }
            }
        }
コード例 #8
0
ファイル: Program.cs プロジェクト: chubin518/Microservice
 public void Dispose()
 {
     clientSocket?.Disconnect(connectionString);
     clientSocket?.Dispose();
 }
コード例 #9
0
        /// <summary>
        /// Disconnects from the server.
        ///  </summary>
        public void Disconnect(bool cancelStreams = true)
        {
            //start by canceling all active real time streams
            if (cancelStreams)
            {
                while (RealTimeDataStreams.Count > 0)
                {
                    CancelRealTimeData(RealTimeDataStreams.First().Instrument);
                }
            }

            _running = false;
            if (_poller != null && _poller.IsStarted)
            {
                _poller.Stop(true);
            }

            if (_heartBeatTimer != null)
            {
                _heartBeatTimer.Stop();
            }

            if (_dealerLoopThread != null && _dealerLoopThread.ThreadState == ThreadState.Running)
            {
                _dealerLoopThread.Join(10);
            }

            if (_reqSocket != null)
            {
                try
                {
                    _reqSocket.Disconnect(string.Format("tcp://{0}:{1}", _host, _realTimeRequestPort));
                }
                catch
                {
                    _reqSocket.Dispose();
                    _reqSocket = null;
                }
            }

            if (_subSocket != null)
            {
                try
                {
                    _subSocket.Disconnect(string.Format("tcp://{0}:{1}", _host, _realTimePublishPort));
                }
                catch
                {
                    _subSocket.Dispose();
                    _subSocket = null;
                }
            }

            if (_dealerSocket != null)
            {
                try
                {
                    _dealerSocket.Disconnect(string.Format("tcp://{0}:{1}", _host, _historicalDataPort));
                }
                catch
                {
                    _dealerSocket.Dispose();
                    _dealerSocket = null;
                }
            }
        }
コード例 #10
0
        /// <summary>
        /// Tries to connect to the QDMS server.
        /// </summary>
        public void Connect()
        {
            Dispose();

            _context      = NetMQContext.Create();
            _reqSocket    = _context.CreateDealerSocket();
            _subSocket    = _context.CreateSubscriberSocket();
            _dealerSocket = _context.CreateSocket(ZmqSocketType.Dealer);

            _reqSocket.Options.Identity    = Encoding.UTF8.GetBytes(_name);
            _subSocket.Options.Identity    = Encoding.UTF8.GetBytes(_name);
            _dealerSocket.Options.Identity = Encoding.UTF8.GetBytes(_name);

            _dealerSocket.ReceiveReady += _dealerSocket_ReceiveReady;
            _reqSocket.ReceiveReady    += _reqSocket_ReceiveReady;
            _subSocket.ReceiveReady    += _subSocket_ReceiveReady;

            _reqSocket.Connect(string.Format("tcp://{0}:{1}", _host, _realTimeRequestPort));

            //start off by sending a ping to make sure everything is regular
            string reply = "";

            try
            {
                _reqSocket.SendMore("");
                _reqSocket.Send("PING");

                _reqSocket.ReceiveString(TimeSpan.FromSeconds(1)); //empty frame starts the REP message //todo receive string?
                reply = _reqSocket.ReceiveString(TimeSpan.FromMilliseconds(50));
            }
            catch
            {
                Dispose();
            }


            if (reply != "PONG") //server didn't reply or replied incorrectly
            {
                _reqSocket.Disconnect(string.Format("tcp://{0}:{1}", _host, _realTimeRequestPort));
                _reqSocket.Close();
                {
                    RaiseEvent(Error, this, new ErrorArgs(-1, "Could not connect to server."));
                    return;
                }
            }

            _lastHeartBeat = DateTime.Now;
            _subSocket.Connect(string.Format("tcp://{0}:{1}", _host, _realTimePublishPort));
            _dealerSocket.Connect(string.Format("tcp://{0}:{1}", _host, _historicalDataPort));

            _running = true;

            //this loop sends out historical data requests and receives the data
            _dealerLoopThread = new Thread(DealerLoop)
            {
                Name = "Client Dealer Loop"
            };
            _dealerLoopThread.Start();

            //this loop takes care of replies to the request socket: heartbeats and data request status messages
            _poller = new Poller();
            _poller.AddSocket(_reqSocket);
            _poller.AddSocket(_subSocket);
            _poller.AddSocket(_dealerSocket);
            Task.Factory.StartNew(_poller.Start, TaskCreationOptions.LongRunning);

            _heartBeatTimer          = new Timer(1000);
            _heartBeatTimer.Elapsed += _timer_Elapsed;
            _heartBeatTimer.Start();
        }
コード例 #11
0
            private async Task Handler()
            {
                while (this.IsRunning)
                {
                    try
                    {
                        using (var socket = new DealerSocket())
                            using (this.BackendBuffer = new NetMQQueue <TransportMessage>())
                                using (var poller = new NetMQPoller()
                                {
                                    socket, this.BackendBuffer
                                })
                                    using (var monitor = new NetMQ.Monitoring.NetMQMonitor(socket, $"inproc://monitor.forwarderdevice.backend.{Guid.NewGuid().ToString()}", SocketEvents.Connected | SocketEvents.Disconnected))
                                    {
                                        socket.Options.Identity = System.Text.Encoding.ASCII.GetBytes(Guid.NewGuid().ToString().Replace("-", "").ToLowerInvariant());

                                        socket.ReceiveReady += (sender, e) =>
                                        {
                                            try
                                            {
                                                var netmqMessage = new NetMQMessage();
                                                if (e.Socket.TryReceiveMultipartMessage(ref netmqMessage))
                                                {
                                                    var message = netmqMessage.ToMessage();

                                                    this.ForwarderDevice.OnBackendReceived(message);

                                                    this.ForwarderDevice.frontendBuffer.Enqueue(message);
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                this.ForwarderDevice.OnDiagnosticMessage(ex.Message + ": " + ex.StackTrace);
                                            }
                                        };

                                        this.BackendBuffer.ReceiveReady += (sender, e) =>
                                        {
                                            try
                                            {
                                                while (this.BackendBuffer.TryDequeue(out TransportMessage message, TimeSpan.Zero))
                                                {
                                                    this.ForwarderDevice.OnFrontendForwarded(message);

                                                    this.ForwarderDevice.OnDiagnosticMessage("Forwarding message to " + this.Endpoint.ToConnectionString());
                                                    if (!socket.TrySendMultipartMessage(TimeSpan.FromSeconds(1), message.ToNetMQMessage()))
                                                    {
                                                        this.ForwarderDevice.OnDiagnosticMessage("Failed to send message");
                                                    }
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                this.ForwarderDevice.OnDiagnosticMessage(ex.Message + ": " + ex.StackTrace);
                                            }
                                        };

                                        monitor.Connected += (sender, e) =>
                                        {
                                            this.ForwarderDevice.OnDiagnosticMessage($"Dealer socket conntected to {this.Endpoint.ToConnectionString()}");
                                            this.IsConnected = true;
                                        };
                                        monitor.Disconnected += (sender, e) =>
                                        {
                                            this.ForwarderDevice.OnDiagnosticMessage($"Dealer socket disconntected from {this.Endpoint.ToConnectionString()}");
                                            this.IsConnected = false;
                                        };

                                        this.ForwarderDevice.OnDiagnosticMessage($"Attempting to connect to {this.Endpoint.ToConnectionString()}");
                                        monitor.StartAsync();
                                        monitor.AttachToPoller(poller);

                                        var pollerTask = new Task(poller.Run);
                                        pollerTask.ContinueWith((Task task) =>
                                        {
                                            var ex = task.Exception;

                                            this.ForwarderDevice.OnDiagnosticMessage(ex.Message + ": " + ex.StackTrace);
                                            this.IsConnected = false;
                                        }, TaskContinuationOptions.OnlyOnFaulted);
                                        pollerTask.Start();

                                        socket.Connect(this.Endpoint.ToConnectionString());

                                        var start = DateTime.Now;
                                        while (!this.IsConnected)
                                        {
                                            if ((DateTime.Now - start).TotalMilliseconds > 5000)
                                            {
                                                throw new Exception($"Connection timeout [{this.ServiceName}]");
                                            }

                                            await Task.Delay(1000);
                                        }

                                        while (this.IsConnected && this.IsRunning)
                                        {
                                            await Task.Delay(1000);
                                        }

                                        this.ForwarderDevice.OnDiagnosticMessage("Closing dealer socket...");
                                        poller.StopAsync();
                                        socket.Disconnect(this.Endpoint.ToConnectionString());
                                        monitor.DetachFromPoller();
                                        monitor.Stop();

                                        this.IsConnected = false;
                                    }

                        if (this.IsRunning)
                        {
                            await Task.Delay(1000);
                        }
                    }
                    catch (Exception ex)
                    {
                        this.ForwarderDevice.OnDiagnosticMessage(ex.Message + ": " + ex.StackTrace);
                    }
                }
            }
コード例 #12
0
ファイル: QDMSClient.cs プロジェクト: minhpascal/qdms
        /// <summary>
        ///     Disconnects from the server.
        /// </summary>
        public void Disconnect(bool cancelStreams = true)
        {
            if (!PollerRunning)
            {
                return;
            }
            // Start by canceling all active real time streams
            if (cancelStreams)
            {
                while (RealTimeDataStreams.Count > 0)
                {
                    CancelRealTimeData(RealTimeDataStreams.First().Instrument);
                }
            }

            _poller?.Stop();
            _poller?.Dispose();

            lock (_realTimeRequestSocketLock)
            {
                if (_realTimeRequestSocket != null)
                {
                    try
                    {
                        _realTimeRequestSocket.Disconnect(_realTimeRequestConnectionString);
                    }
                    finally
                    {
                        _realTimeRequestSocket.ReceiveReady -= RealTimeRequestSocketReceiveReady;
                        _realTimeRequestSocket.Close();
                        _realTimeRequestSocket = null;
                    }
                }
            }

            lock (_realTimeDataSocketLock)
            {
                if (_realTimeDataSocket != null)
                {
                    try
                    {
                        _realTimeDataSocket.Disconnect(_realTimeDataConnectionString);
                    }
                    finally
                    {
                        _realTimeDataSocket.ReceiveReady -= RealTimeDataSocketReceiveReady;
                        _realTimeDataSocket.Close();
                        _realTimeDataSocket = null;
                    }
                }
            }

            lock (_historicalDataSocket)
            {
                if (_historicalDataSocket != null)
                {
                    try
                    {
                        _historicalDataSocket.Disconnect(_historicalDataConnectionString);
                    }
                    finally
                    {
                        _historicalDataSocket.ReceiveReady -= HistoricalDataSocketReceiveReady;
                        _historicalDataSocket.Close();
                        _historicalDataSocket = null;
                    }
                }
            }

            _poller = null;
        }
コード例 #13
0
ファイル: QDMSClient.cs プロジェクト: minhpascal/qdms
        /// <summary>
        ///     Tries to connect to the QDMS server.
        /// </summary>
        public void Connect()
        {
            if (Connected)
            {
                return;
            }

            lock (_realTimeRequestSocketLock)
            {
                _realTimeRequestSocket = new DealerSocket(_realTimeRequestConnectionString);
                _realTimeRequestSocket.Options.Identity = Encoding.UTF8.GetBytes(_name);
                // Start off by sending a ping to make sure everything is regular
                var reply = string.Empty;

                try
                {
                    _realTimeRequestSocket.SendMoreFrame(string.Empty).SendFrame(MessageType.Ping);

                    if (_realTimeRequestSocket.TryReceiveFrameString(TimeSpan.FromSeconds(1), out reply))
                    {
                        _realTimeRequestSocket.TryReceiveFrameString(TimeSpan.FromMilliseconds(50), out reply);
                    }
                }
                catch
                {
                    Disconnect();
                }

                if (reply == null || !reply.Equals(MessageType.Pong, StringComparison.InvariantCultureIgnoreCase))
                {
                    try
                    {
                        _realTimeRequestSocket.Disconnect(_realTimeRequestConnectionString);
                    }
                    finally
                    {
                        _realTimeRequestSocket.Close();
                        _realTimeRequestSocket = null;
                    }

                    RaiseEvent(Error, this, new ErrorArgs(-1, "Could not connect to server."));

                    return;
                }

                _realTimeRequestSocket.ReceiveReady += RealTimeRequestSocketReceiveReady;
            }

            lock (_realTimeDataSocketLock)
            {
                _realTimeDataSocket = new SubscriberSocket(_realTimeDataConnectionString);
                _realTimeDataSocket.Options.Identity = Encoding.UTF8.GetBytes(_name);
                _realTimeDataSocket.ReceiveReady    += RealTimeDataSocketReceiveReady;
            }

            lock (_historicalDataSocketLock)
            {
                _historicalDataSocket = new DealerSocket(_historicalDataConnectionString);
                _historicalDataSocket.Options.Identity = Encoding.UTF8.GetBytes(_name);
                _historicalDataSocket.ReceiveReady    += HistoricalDataSocketReceiveReady;
            }

            _lastHeartBeat = DateTime.Now;

            _heartBeatTimer          = new NetMQTimer(TimeSpan.FromSeconds(HeartBeatPeriodInSeconds));
            _heartBeatTimer.Elapsed += HeartBeatTimerElapsed;

            _historicalDataTimer          = new NetMQTimer(TimeSpan.FromSeconds(HistoricalDataRequestsPeriodInSeconds));
            _historicalDataTimer.Elapsed += HistoricalDataTimerElapsed;

            _poller = new NetMQPoller {
                _realTimeRequestSocket, _realTimeDataSocket, _historicalDataSocket, _heartBeatTimer, _historicalDataTimer
            };

            _poller.RunAsync();
        }