Beispiel #1
0
 /// <summary>
 ///     Dispose resources
 /// </summary>
 public void Dispose()
 {
     _actor?.Dispose();
     _connectionDisposable?.Dispose();
     _reqSocket?.Dispose();
     _disposables?.Dispose();
 }
Beispiel #2
0
        public void Dispose()
        {
            Disconnect();

            if (_reqSocket != null)
            {
                _reqSocket.Dispose();
                _reqSocket = null;
            }
            if (_subSocket != null)
            {
                _subSocket.Dispose();
                _subSocket = null;
            }
            if (_dealerSocket != null)
            {
                _dealerSocket.Dispose();
                _dealerSocket = null;
            }
            if (_heartBeatTimer != null)
            {
                _heartBeatTimer.Dispose();
                _heartBeatTimer = null;
            }
            //The context must be disposed of last! It will hang if the sockets have not been disposed.
            if (_context != null)
            {
                _context.Dispose();
                _context = null;
            }
        }
        /// <summary>
        ///     send a request to a broker for a specific service and receive the reply
        ///
        ///     if the reply is not available within a specified time
        ///     the client deems the connection as lost and reconnects
        ///     for a specified number of times. if no reply is available
        ///     throughout this procedure the client abandons
        ///     the reply is checked for validity and returns the reply
        ///     according to the verbose flag it reports about its activities
        /// </summary>
        /// <param name="serviceName">the name of the service requested</param>
        /// <param name="request">the request message to process by service</param>
        /// <returns>the reply from service</returns>
        /// <exception cref="ApplicationException">malformed message received</exception>
        /// <exception cref="ApplicationException">malformed header received</exception>
        /// <exception cref="ApplicationException">reply received from wrong service</exception>
        public NetMQMessage Send(string serviceName, NetMQMessage request)
        {
            if (string.IsNullOrWhiteSpace(serviceName))
            {
                throw new ApplicationException("serviceName must not be empty or null.");
            }

            if (ReferenceEquals(request, null))
            {
                throw new ApplicationException("the request must not be null");
            }
            // memorize it for the event handler
            m_serviceName = serviceName;

            // if for any reason the socket is NOT connected -> connect it!
            if (!m_connected)
            {
                Connect();
            }

            var message = new NetMQMessage(request);

            // prefix the request according to MDP specs
            // Frame 1: "MDPCxy" (six bytes MDP/Client x.y)
            // Frame 2: service name as printable string
            // Frame 3: request
            message.Push(serviceName);
            message.Push(m_mdpClient);

            Log(string.Format("[CLIENT INFO] sending {0} to service {1}", message, serviceName));

            var retiesLeft = Retries;

            while (retiesLeft > 0)
            {
                // beware of an exception if broker has not picked up the message at all
                // because one can not send multiple times! it is strict REQ -> REP -> REQ ...
                m_client.SendMultipartMessage(message);

                // Poll -> see ReceiveReady for event handling
                if (m_client.Poll(Timeout))
                {
                    // set by event handler
                    return(m_reply);
                }
                // if it failed assume communication dead and re-connect
                if (--retiesLeft > 0)
                {
                    Log("[CLIENT WARNING] no reply, reconnecting ...");

                    Connect();
                }
            }

            Log("[CLIENT ERROR] permanent error, abandoning!");

            m_client.Dispose();

            return(null);
        }
Beispiel #4
0
    public bool sendAndReceive(ref NetMQ.Msg req_msg, ref NetMQ.Msg resp_msg)
    {
        if (socket == null)
        {
            reconnect();
        }

        StdMessage m = new StdMessage(req_msg.Data[1], req_msg.Data[2]);

        NetMQ.Msg copy = new NetMQ.Msg();
        bool      ok   = false;

        for (uint i = 0; i < retries; i++)
        {
            copy.Copy(ref req_msg);

            // send
            if (!socket.TrySend(ref copy, TimeSpan.FromMilliseconds(min_trysend_ms), false))
            {
                ok = false;
                UnityEngine.Debug.Log("ReliableExternalClient: could not send");
                break;

                //TODO: clear enqueued messages when server is offline
            }
            //UnityEngine.Debug.Log("ReliableExternalClient: request sent " + m.to_string());

            // receive
            if (socket.TryReceive(ref resp_msg, timeout))
            {
                ok = true;
                // UnityEngine.Debug.Log("ReliableExternalClient: response received "
                //+ new StdMessage(resp_msg.Data[1], resp_msg.Data[2]).to_string());
                break;
            }

            //UnityEngine.Debug.Log(String.Format("ReliableExternalClient: no response from server {0}. Retrying", srvAddress));
            reconnect();
        }

        if (!ok)
        {
            UnityEngine.Debug.Log(String.Format("ReliableExternalClient: server {0} seems to be offline. Abandoning", srvAddress));
        }

        copy.Close();
        socket.Dispose();  //call Dispose on all sockets before cleanup the netmq context
        socket.Close();

        socket = null;

        if (socket == null)
        {
            UnityEngine.Debug.Log("ReliableExternalClient: socket closed and null");
        }

        return(ok);
    }
Beispiel #5
0
        //tells the servers to stop running and waits for the threads to shut down.
        public void StopServer()
        {
            if (_poller != null && _poller.IsStarted)
            {
                _poller.Stop(true);
            }

            //clear the socket and context and say it's not running any more
            if (_pubSocket != null)
            {
                _pubSocket.Dispose();
            }
            ServerRunning = false;
        }
Beispiel #6
0
        public string Request(string service, string msg, int timeoutmsec)
        {
            string      resp    = string.Empty;
            LinkAddress address = config.ReqRep.FindLinkAddress(service);

            if (address == null)
            {
                return(resp);
            }

            bool   pollResult = false;
            string requestId  = Guid.NewGuid().ToString();

            using (NetMQContext context = NetMQContext.Create())
            {
                NetMQSocket client = context.CreateRequestSocket();
                client.Options.Linger   = TimeSpan.Zero;
                client.Options.Identity = Encoding.UTF8.GetBytes(requestId);
                client.Connect(address.Address);
                try
                {
                    byte[] data = Encoding.UTF8.GetBytes(msg);
                    client.Send(data);
                }
                catch (Exception)
                {
                    client.Disconnect(address.Address);
                    client.Dispose();
                    return(resp);
                }

                client.ReceiveReady += ClientOnReceiveReady;
                pollResult           = client.Poll(TimeSpan.FromMilliseconds(timeoutmsec));
                client.ReceiveReady -= ClientOnReceiveReady;
                client.Disconnect(address.Address);
                client.Dispose();
            }

            if (pollResult)
            {
                if (responseMsgs.ContainsKey(requestId))
                {
                    responseMsgs.TryRemove(requestId, out resp);
                }
            }

            return(resp);
        }
Beispiel #7
0
        /// <summary>
        /// Release and dispose of any contained resources.
        /// </summary>
        /// <param name="disposing">true if releasing managed resources</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            bool attachedToPoller = m_attachedPoller != null;

            if (attachedToPoller)
            {
                DetachFromPoller(m_ownsMonitoringSocket);
            }
            else if (!m_isStoppedEvent.WaitOne(0))
            {
                Stop();
            }

            m_monitoringSocket.ReceiveReady -= Handle;

#if NET35
            m_isStoppedEvent.Close();
#else
            m_isStoppedEvent.Dispose();
#endif

            if (m_ownsMonitoringSocket && !attachedToPoller)
            {
                m_monitoringSocket.Dispose();
            }
        }
Beispiel #8
0
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_publisherSocket != null)
                {
                    _publisherSocket.Dispose();
                    _publisherSocket = null;
                }

                foreach (NetMQSocket subscriber in _subscriberSockets.ToArray())
                {
                    subscriber.Dispose();
                    _subscriberSockets.Remove(subscriber);
                }

                // Setting running to false will stop the subscriber tasks
                _running = false;

                if (_context != null)
                {
                    _context.Dispose();
                    _context = null;
                }
            }
            base.Dispose(disposing);
        }
Beispiel #9
0
 public void Dispose()
 {
     Socket.ReceiveReady -= ReceiveReady;
     Socket.SendReady    -= SendReady;
     _factory.RemoveSocket(Socket);
     Socket.Dispose();
 }
Beispiel #10
0
 public void OnApplicationQuit()
 {
     receiver.Dispose();
     sender.Dispose();
     response.Dispose();
     NetMQConfig.Cleanup();
 }
        /// <summary>
        /// Release and dispose of any contained resources.
        /// </summary>
        /// <param name="disposing">true if releasing managed resources</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            if (m_attachedPoller != null)
            {
                DetachFromPoller();
            }
            else if (!m_isStoppedEvent.WaitOne(0))
            {
                Stop();
            }

            m_monitoringSocket.ReceiveReady -= Handle;

            m_isStoppedEvent.Close();

            if (m_ownsMonitoringSocket)
            {
                m_monitoringSocket.Dispose();
            }
        }
Beispiel #12
0
    /// <summary>
    /// 套接字循环, 在背景线程中运行
    /// </summary>
    private void SocketLoop()
    {
#if UNITY_EDITOR
        // use this to avoid freeze when reload script with (a) scenes running
        UnityEditor.AssemblyReloadEvents.beforeAssemblyReload += ClearSocket;
#endif
        // 初始化AsyncIO
        AsyncIO.ForceDotNet.Force();
        terminated = false;
        using (socket = new PullSocket(ConfigManager.instance.Current.mazeEditorAddress))
        {
            try
            {
                FrameStringProcess(socket.ReceiveFrameString());
                while (!terminated)
                {
                    FrameStringProcess(socket.ReceiveFrameString());
                }
            }
            catch (TerminatingException)
            {
                Debug.Log("Socket terminated.");
            }
            finally
            {
                socket.Dispose();
                NetMQConfig.Cleanup();
            }
        }
    }
Beispiel #13
0
 /// <summary>
 /// Releases unmanaged and - optionally - managed resources.
 /// </summary>
 /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
 private void Dispose(bool disposing)
 {
     if (disposing && socket != null)
     {
         socket.Dispose();
         socket = null;
     }
 }
Beispiel #14
0
 /// <summary>
 ///
 /// </summary>
 public void Stop()
 {
     if (m_started)
     {
         m_poller.Dispose();
         m_server.Dispose();
         m_started = false;
     }
 }
 public void Dispose()
 {
     _clientSocket.Dispose();
     _context.Dispose();
     if (task != null)
     {
         task.Dispose();
     }
 }
 public Task StopAsync(CancellationToken cancellationToken)
 {
     _routerSocket.Dispose();
     _dealerSocket.Dispose();
     _poller.StopAsync();
     _workerPoller.StopAsync();
     NetMQConfig.Cleanup(false);
     return(Task.CompletedTask);
 }
Beispiel #17
0
 public void Dispose()
 {
     _isStart = false;
     _serverSocket.Dispose();
     _context.Dispose();
     if (task != null)
     {
         task.Dispose();
     }
 }
Beispiel #18
0
        protected override void StopConnection()
        {
            socket.Disconnect("tcp://localhost:5555");

            Debug.Log("Stopping Connection");

            socket.Dispose();
            NetMQConfig.Cleanup();
            isRunning = false;
        }
Beispiel #19
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            // m_poller might not have been created yet!
            if (!ReferenceEquals(m_poller, null))
            {
                m_poller.Dispose();
            }

            // m_client might not have been created yet!
            if (!ReferenceEquals(m_client, null))
            {
                m_client.Dispose();
            }
        }
Beispiel #20
0
        protected override void Dispose(bool disposing)
        {
            if (publisher != null)
            {
                publisher.Dispose();
                publisher = null;
            }

            base.Dispose(disposing);
        }
Beispiel #21
0
 public void Dispose()
 {
     if (Interlocked.Increment(ref _disposeCount) != 1)
     {
         return;
     }
     Debug.WriteLine(string.Format("Disposing {0} ({1:x})...", this.GetType().Name, this.GetHashCode()));
     new Action(() => _socket.Options.Linger = TimeSpan.Zero).CaptureMqExceptions <TerminatingException>();
     new Action(() => _socket.Dispose()).CaptureMqExceptions();
     Console.WriteLine(string.Format("{0} disposed ({1:x}).", this.GetType().Name, this.GetHashCode()));
 }
Beispiel #22
0
 public void Dispose()
 {
     _source?.Cancel(true);
     while (_task != default && !_task.IsCanceled && !_task.IsCompleted && !_task.IsFaulted)
     {
         _stopping.WaitOne(10);
     }
     _outgoing?.Dispose();
     _stopping?.Dispose();
     _task?.Dispose();
 }
Beispiel #23
0
 protected virtual void Dispose(bool disposing)
 {
     if (!_IsDisposed)
     {
         if (disposing)
         {
             Poller?.Dispose();
             Socket?.Dispose();
         }
         _IsDisposed = true;
     }
 }
Beispiel #24
0
        protected override void Dispose(bool disposing)
        {
            if (disposing && !this._isDisposed)
            {
                StopJob();

                _subscriber.Dispose();
                _publisher.Dispose();

                this._isDisposed = true;
            }
            base.Dispose(disposing);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposedValue)
            {
                if (disposing)
                {
                    _socket.Dispose();
                    _socket = null;
                }

                _disposedValue = true;
            }
        }
 public void Dispose()
 {
     if (frontend != null)
     {
         frontend.Close();
         frontend.Dispose();
     }
     if (backend != null)
     {
         backend.Close();
         backend.Dispose();
     }
 }
Beispiel #27
0
        protected override void Dispose(bool disposing)
        {
            if (disposing && socket != null)
            {
                socket.Dispose();
                socket = null;
            }

            if (disposing && context != null)
            {
                context.Dispose();
                context = null;
            }
        }
Beispiel #28
0
        public static void Blow(string song, string notes)
        {
            new Thread(() => {
                using (NetMQSocket request_socket = context.CreateRequestSocket()) {
                    request_socket.Connect(string.Format("tcp://{0}:{1}", Address, RequestPort));
                    request_socket.SendMore("blow").SendMore(song).Send(notes);

                    string response = request_socket.ReceiveString();
                    Console.WriteLine("[request_socket] Response: {0}", response);

                    request_socket.Close();
                    request_socket.Dispose();
                }
            }).Start();
        }
Beispiel #29
0
        public void Dispose()
        {
            StopServer();

            if (_routerSocket != null)
            {
                _routerSocket.Dispose();
                _routerSocket = null;
            }
            if (_context != null)
            {
                _context.Dispose();
                _context = null;
            }
        }
Beispiel #30
0
 protected virtual void Dispose(bool disposing)
 {
     if (!listenTask.IsCompleted)
     {
         listenCancelToken.Cancel();
         if (listener != null)
         {
             listener.Dispose();
         }
         this.Context.Dispose();
         try
         {
             listenTask.Wait(listenTimeout);
         }
         catch { }
     }
 }