A PairSocket is a NetMQSocket, usually used to synchronize two threads - using only one socket on each side.
상속: NetMQSocket
예제 #1
0
        public void Run(PairSocket shim)
        {
            shim.SignalOK();

            while (true)
            {
                try
                {
                    NetMQMessage msg = shim.ReceiveMultipartMessage();

                    string command = msg[0].ConvertToString();

                    if (command == NetMQActor.EndShimMessage)
                        break;

                    //Simulate a failure that should be sent back to Actor                    
                    throw new InvalidOperationException("Actors Shim threw an Exception");
                }
                //You WILL need to decide what Exceptions should be caught here, this is for 
                //demonstration purposes only, any unhandled fault will bubble up to caller's code
                catch (InvalidOperationException e)
                {
                    shim.SendFrame(string.Format("Error: Exception occurred {0}", e.Message));
                }
            }
        }
예제 #2
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.");

        pairSocket = new NetMQ.Sockets.PairSocket();
        pairSocket.Options.ReceiveHighWatermark = 0;
        //pairSocket.Connect("tcp://192.168.1.122:55555");
        pairSocket.Connect("tcp://192.168.1.111:55555");

        is_connected = true;

        while (is_connected && stop_thread_ == false)
        {
            is_connected = pairSocket.TryReceiveFrameString(timeout, out msg);
            pairSocket.TrySendFrame(timeout, final);
        }

        pairSocket.Close();
        Debug.Log("ContextTerminate.");
        NetMQConfig.ContextTerminate();
        NetMQConfig.Cleanup();
    }
예제 #3
0
        /// <summary>
        /// Create and return an inproc pipe where socket1 is bound and socket2 is connected.
        /// </summary>
        /// <param name="socket1">the Bind socket</param>
        /// <param name="socket2">the Connect socket</param>
        public static void CreateSocketPair(out PairSocket socket1, out PairSocket socket2)
        {
            string address = $"inproc://NetMQSocketPair#{Interlocked.Increment(ref s_sequence)}";

            socket1 = new PairSocket();
            socket1.Bind(address);

            socket2 = new PairSocket();
            socket2.Connect(address);
        }
예제 #4
0
파일: PairSocket.cs 프로젝트: hdxhan/netmq
        public static void CreateSocketPair(out PairSocket socket1, out PairSocket socket2)
        {
            string address = string.Format("inproc://NetMQSocketPair#{0}", Interlocked.Increment(ref s_sequence));

            socket1 = new PairSocket();
            socket1.Bind(address);

            socket2 = new PairSocket();
            socket2.Connect(address);
        }
예제 #5
0
        protected WSSocket(NetMQContext context, IShimHandler<int> shimHandler )
        {
            int id = Interlocked.Increment(ref s_id);
            m_context = context;

            m_messagesPipe = context.CreatePairSocket();
            m_messagesPipe.Bind(string.Format("inproc://wsrouter-{0}", id));

            m_messagesPipe.ReceiveReady += OnMessagePipeReceiveReady;

            m_actor = new Actor<int>(context, shimHandler, id);

            m_messagesPipe.WaitForSignal();
        }
예제 #6
0
            public void RunPipeline(Sockets.PairSocket shim)
            {
                m_pipe = shim;

                shim.SignalOK();

                while (!m_terminated)
                {
                    PollItem[] pollItems = new PollItem[]
                    {
                        new PollItem(m_pipe.SocketHandle, PollEvents.PollIn),
                        new PollItem(m_udpSocket, PollEvents.PollIn),
                    };

                    long timeout = -1;

                    if (m_transmit != null)
                    {
                        timeout = m_pingAt - Clock.NowMs();

                        if (timeout < 0)
                        {
                            timeout = 0;
                        }
                    }

                    ZMQ.Poll(pollItems, m_udpSocket != null ? 2 : 1, (int)timeout);

                    if (pollItems[0].ResultEvent.HasFlag(PollEvents.PollIn))
                    {
                        HandlePipe();
                    }

                    if (pollItems[1].ResultEvent.HasFlag(PollEvents.PollIn))
                    {
                        HandleUdp();
                    }

                    if (m_transmit != null && Clock.NowMs() > m_pingAt)
                    {
                        SendUdpFrame(m_transmit);
                        m_pingAt = Clock.NowMs() + m_interval;
                    }
                }

                m_udpSocket.Dispose();
            }
예제 #7
0
        void IShimHandler.Run(PairSocket shim)
        {
            Poller = new NetMQPoller();


            Shim = shim;
            Shim.ReceiveReady += OnShimReady;
            Poller.Add(Shim);

            Initialize();

            Shim.SignalOK();

            Poller.Run();

            Cleanup();
        }
예제 #8
0
        public void Run(PairSocket shim)
        {
            shim.SignalOK();

            while (true)
            {
                try
                {
                    //Message for this actor/shim handler is expected to be
                    //Frame[0] : Command
                    //Frame[2] : AccountAction as JSON
                    //Frame[1] : Account as JSON
                    //
                    //Result back to actor is a JSON message of the amended Account
                    NetMQMessage msg = shim.ReceiveMultipartMessage();

                    string command = msg[0].ConvertToString();

                    if (command == NetMQActor.EndShimMessage)
                        break;

                    if (msg[0].ConvertToString() == "AMEND ACCOUNT")
                    {
                        string accountActionJson = msg[1].ConvertToString();
                        var accountAction = JsonConvert.DeserializeObject<AccountAction>(accountActionJson);

                        string accountJson = msg[2].ConvertToString();
                        var account = JsonConvert.DeserializeObject<Account>(accountJson);
                        AmmendAccount(accountAction, account);
                        shim.Send(JsonConvert.SerializeObject(account));
                    }
                    else
                    {
                        shim.Send("Error: invalid message to actor");
                    }
                }
                // You WILL need to decide what Exceptions should be caught here, this is for
                // demonstration purposes only, any unhandled fault will bubble up to caller's code.
                catch (Exception e)
                {
                    shim.Send(string.Format("Error: Exception occurred {0}", e.Message));
                }
            }
        }
예제 #9
0
    //this coroutine connects to ramulator and communicates how ramulator expects it to
    //in order to start the experiment session.  follow it up with BeginNewTrial and
    //SetState calls
    public IEnumerator BeginNewSession(int sessionNumber)
    {
        //Connect to ramulator///////////////////////////////////////////////////////////////////
        zmqSocket = new NetMQ.Sockets.PairSocket();
        zmqSocket.Bind(address);
        //Debug.Log ("socket bound");


        yield return(WaitForMessage("CONNECTED", "Ramulated not connected."));


        //SendSessionEvent//////////////////////////////////////////////////////////////////////
        System.Collections.Generic.Dictionary <string, object> sessionData = new Dictionary <string, object>();
        sessionData.Add("name", UnityEPL.GetExperimentName());
        sessionData.Add("version", Application.version);
        sessionData.Add("subject", UnityEPL.GetParticipants()[0]);
        sessionData.Add("session_number", sessionNumber.ToString());
        DataPoint sessionDataPoint = new DataPoint("SESSION", DataReporter.RealWorldTime(), sessionData);

        SendMessageToRamulator(sessionDataPoint.ToJSON());
        yield return(null);


        //Begin Heartbeats///////////////////////////////////////////////////////////////////////
        InvokeRepeating("SendHeartbeat", 0, 1);


        //SendReadyEvent////////////////////////////////////////////////////////////////////
        DataPoint ready = new DataPoint("READY", DataReporter.RealWorldTime(), new Dictionary <string, object>());

        SendMessageToRamulator(ready.ToJSON());
        yield return(null);


        yield return(WaitForMessage("START", "Start signal not received"));


        InvokeRepeating("ReceiveHeartbeat", 0, 1);
    }
예제 #10
0
        public void Run(PairSocket shim)
        {
            shim.SignalOK();

            while (true)
            {
                try
                {
                    //Message for this actor/shim handler is expected to be 
                    //Frame[0] : Command
                    //Frame[1] : Payload
                    //
                    //Result back to actor is a simple echoing of the Payload, where
                    //the payload is prefixed with "ECHO BACK "
                    NetMQMessage msg = shim.ReceiveMultipartMessage();

                    string command = msg[0].ConvertToString();

                    if (command == NetMQActor.EndShimMessage)
                        break;

                    if (command == "ECHO")
                    {
                        shim.SendFrame(string.Format("ECHO BACK : {0}", msg[1].ConvertToString()));
                    }
                    else
                    {
                        shim.SendFrame("Error: invalid message to actor");
                    }
                }
                // You WILL need to decide what Exceptions should be caught here, this is for 
                // demonstration purposes only, any unhandled fault will bubble up to caller's code
                catch (Exception e)
                {
                    shim.SendFrame(string.Format("Error: Exception occurred {0}", e.Message));
                }
            }
        }
예제 #11
0
            public void RunPipeline(Sockets.PairSocket shim)
            {
                m_pipe = shim;

                shim.SignalOK();

                m_pipe.ReceiveReady += OnPipeReady;

                m_pingTimer          = new NetMQTimer(0);
                m_pingTimer.Elapsed += PingElapsed;
                m_pingTimer.Enable   = false;

                m_poller = new Poller();
                m_poller.AddSocket(m_pipe);
                m_poller.AddTimer(m_pingTimer);

                m_poller.Start();

                // the beacon might never been configured
                if (m_udpSocket != null)
                {
                    m_udpSocket.Dispose();
                }
            }
예제 #12
0
 public Shim(IShimHandler shimHandler, PairSocket pipe)
 {
     this.Handler = shimHandler;
     this.Pipe = pipe;
 }
예제 #13
0
        /// <summary>
        /// Release any contained resources.
        /// </summary>
        /// <param name="disposing">true if managed resources are to be released</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
                return;

            if (_actor != null)
            {
                _actor.Dispose();
                _actor = null;
            }
            if (_inbox != null)
            {
                _inbox.Dispose();
                _inbox = null;
            }
        }
예제 #14
0
        /// <summary>
        /// This method is being run asynchronously by m_actor.
        /// </summary>
        /// <param name="shim"></param>
        private void RunActor(PairSocket shim)
        {
            _pipe = shim;
            _pipe.ReceiveReady += OnPipeReceiveReady;

            var reapTimer = new NetMQTimer(TimeSpan.FromMilliseconds(1000));
            reapTimer.Elapsed += OnReapTimerElapsed;

            // Start poller, but poll only the _pipe. Start() and Stop() will add/remove other items to poll
            _poller = new NetMQPoller { _pipe, reapTimer };

            // Signal the actor that we're ready to work
            _pipe.SignalOK();

            // polling until cancelled
            _poller.Run();

            reapTimer.Enable = false;
            reapTimer.Elapsed -= OnReapTimerElapsed;
        }
예제 #15
0
        /// <summary>
        /// Release any contained resources.
        /// </summary>
        /// <param name="disposing">true if managed resources are to be released</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
                return;

            if (_outbox != null)
            {
                _outbox.Dispose();
                _outbox = null;
            }
            if (_poller != null)
            {
                _poller.Stop();
                _poller.Dispose();
                _poller = null;
            }
            if (_beacon != null)
            {
                _beacon.Dispose();
                _beacon = null;
            }
            if (_inbox != null)
            {
                _inbox.Dispose();
                _inbox = null;
            }
            foreach (var peer in _peers.Values)
            {
                peer.Destroy();
            }
            foreach (var group in _peerGroups.Values)
            {
                group.Dispose();
            }
            foreach (var group in _ownGroups.Values)
            {
                group.Dispose();
            }
        }
예제 #16
0
        private ZreNode(PairSocket outbox)
        {
            _inbox = new RouterSocket();

            //  Use ZMQ_ROUTER_HANDOVER so that when a peer disconnects and
            //  then reconnects, the new client connection is treated as the
            //  canonical one, and any old trailing commands are discarded.
            // NOTE: This RouterHandover option apparently doesn't exist in NetMQ 
            //      so I IGNORE it for now. DaleBrubaker Feb 1 2016

            _outbox = outbox;
            //_beaconPort = ZreDiscoveryPort;
            _interval = TimeSpan.Zero; // Use default
            _uuid = Guid.NewGuid();
            _peers = new Dictionary<Guid, ZrePeer>();
            _peerGroups = new Dictionary<string, ZreGroup>();
            _ownGroups = new Dictionary<string, ZreGroup>();
            _headers = new Dictionary<string, string>();

            //  Default name for node is first 6 characters of UUID:
            //  the shorter string is more readable in logs
            _name = _uuid.ToString().ToUpper().Substring(0, 6);

            _actor = NetMQActor.Create(RunActor);
        }
예제 #17
0
 /// <summary>
 /// Create a new node and return the actor that controls it.
 /// All node control is done through _actor.
 /// outbox is passed to ZreNode for sending Zyre message traffic back to caller.
 /// </summary>
 /// <param name="outbox"></param>
 /// <returns></returns>
 public static NetMQActor Create(PairSocket outbox)
 {
     var node = new ZreNode(outbox);
     return node._actor;
 }
예제 #18
0
파일: ZyreNode.cs 프로젝트: NetMQ/Zyre
        private ZyreNode(PairSocket outbox, Action<string> loggerDelegate = null)
        {
            _outbox = outbox;
            _loggerDelegate = loggerDelegate;

            _beaconPort = ZreDiscoveryPort;
            _interval = TimeSpan.Zero; // Use default
            _uuid = Guid.NewGuid();
            _peers = new Dictionary<Guid, ZyrePeer>();
            _peerGroups = new Dictionary<string, ZyreGroup>();
            _ownGroups = new Dictionary<string, ZyreGroup>();
            _headers = new Dictionary<string, string>();

            //  Default name for node is first 6 characters of UUID:
            //  the shorter string is more readable in logs
            _name = _uuid.ToShortString6();

            //  Use ZMQ_ROUTER_HANDOVER so that when a peer disconnects and
            //  then reconnects, the new client connection is treated as the
            //  canonical one, and any old trailing commands are discarded.
            //  This RouterHandover option is currently not supported in NetMQ Feb 16 2016
            
            _actor = NetMQActor.Create(RunActor);
        }
예제 #19
0
파일: ZyreNode.cs 프로젝트: NetMQ/Zyre
        /// <summary>
        /// Create a new node and return the actor that controls it.
        /// All node control is done through _actor.
        /// outbox is passed to ZyreNode for sending Zyre message traffic back to caller.
        /// </summary>
        /// <param name="outbox">the pipe for sending messages from peers back to Zyre.cs</param>
        /// <param name="loggerDelegate">An action to take for logging when _verbose is true. Default is null.</param>
        /// <returns>the _actor, or null if not successful</returns>
        internal static NetMQActor Create(PairSocket outbox, Action<string> loggerDelegate = null)
        {
            var node = new ZyreNode(outbox, loggerDelegate);

            return node._actor;
        }