示例#1
0
        public static SessionBase Create(IOThread ioThread, bool connect,
                                         SocketBase socket, Options options, Address addr)
        {
            SessionBase s;

            switch (options.SocketType)
            {
            case ZmqSocketType.Req:
                s = new Req.ReqSession(ioThread, connect, socket, options, addr);
                break;

            case ZmqSocketType.Dealer:
                s = new Dealer.DealerSession(ioThread, connect, socket, options, addr);
                break;

            case ZmqSocketType.Rep:
                s = new Rep.RepSession(ioThread, connect, socket, options, addr);
                break;

            case ZmqSocketType.Router:
                s = new Router.RouterSession(ioThread, connect, socket, options, addr);
                break;

            case ZmqSocketType.Pub:
                s = new Pub.PubSession(ioThread, connect, socket, options, addr);
                break;

            case ZmqSocketType.Xpub:
                s = new XPub.XPubSession(ioThread, connect, socket, options, addr);
                break;

            case ZmqSocketType.Sub:
                s = new Sub.SubSession(ioThread, connect, socket, options, addr);
                break;

            case ZmqSocketType.Xsub:
                s = new XSub.XSubSession(ioThread, connect, socket, options, addr);
                break;

            case ZmqSocketType.Push:
                s = new Push.PushSession(ioThread, connect, socket, options, addr);
                break;

            case ZmqSocketType.Pull:
                s = new Pull.PullSession(ioThread, connect, socket, options, addr);
                break;

            case ZmqSocketType.Pair:
                s = new Pair.PairSession(ioThread, connect, socket, options, addr);
                break;

            case ZmqSocketType.Stream:
                s = new Stream.StreamSession(ioThread, connect, socket, options, addr);
                break;

            default:
                throw new InvalidException("type=" + options.SocketType);
            }
            return(s);
        }
示例#2
0
        public PgmListener(IOThread ioThread, SocketBase socket, Options options)
            : base(ioThread, options)
        {
            m_socket = socket;

            m_ioObject = new IOObject(ioThread);
        }
示例#3
0
 public IOObject(IOThread ioThread)
 {
     if (ioThread != null)
     {
         Plug(ioThread);
     }
 }
示例#4
0
 public IOObject(IOThread ioThread)
 {
     if (ioThread != null)
     {
         Plug(ioThread);
     }
 }
示例#5
0
        //  Returns the I/O thread that is the least busy at the moment.
        //  Affinity specifies which I/O threads are eligible (0 = all).
        //  Returns NULL if no I/O thread is available.
        public IOThread ChooseIOThread(long affinity)
        {
            if (m_ioThreads.Count == 0)
            {
                return(null);
            }

            //  Find the I/O thread with minimum load.
            int      minLoad          = -1;
            IOThread selectedIOThread = null;

            for (int i = 0; i != m_ioThreads.Count; i++)
            {
                if (affinity == 0 || (affinity & (1L << i)) > 0)
                {
                    int load = m_ioThreads[i].Load;
                    if (selectedIOThread == null || load < minLoad)
                    {
                        minLoad          = load;
                        selectedIOThread = m_ioThreads[i];
                    }
                }
            }
            return(selectedIOThread);
        }
示例#6
0
        public PgmListener(IOThread ioThread, SocketBase socket, Options options)
            : base(ioThread, options)
        {
            m_socket = socket;

            m_ioObject = new IOObject(ioThread);
        }
示例#7
0
 public IOObject([CanBeNull] IOThread ioThread)
 {
     if (ioThread != null)
     {
         Plug(ioThread);
     }
 }
示例#8
0
        public void Plug(IOThread ioThread,
                         SessionBase session)
        {
            Debug.Assert(!m_plugged);
            m_plugged = true;

            //  Connect to session object.
            Debug.Assert(m_session == null);
            Debug.Assert(session != null);
            m_session = session;
            m_socket  = m_session.Socket;

            m_ioObject = new IOObject(null);
            m_ioObject.SetHandler(this);
            //  Connect to I/O threads poller object.
            m_ioObject.Plug(ioThread);
            m_ioObject.AddFd(m_handle);

            //  Send the 'length' and 'flags' fields of the identity message.
            //  The 'length' field is encoded in the long format.

            m_greetingOutputBuffer[m_outsize++] = ((byte)0xff);
            m_greetingOutputBuffer.PutLong(m_options.Endian, (long)m_options.IdentitySize + 1, 1);
            m_outsize += 8;
            m_greetingOutputBuffer[m_outsize++] = ((byte)0x7f);

            m_outpos = new ByteArraySegment(m_greetingOutputBuffer);

            m_ioObject.SetPollin(m_handle);
            m_ioObject.SetPollout(m_handle);

            //  Flush all the data that may have been already received downstream.
            InEvent();
        }
示例#9
0
        public SessionBase(IOThread ioThread, bool connect,
                                             SocketBase socket, Options options, Address addr)
            : base(ioThread, options)
        {
            m_ioObject = new IOObject(ioThread);

            m_connect = connect;
            m_pipe = null;
            m_incompleteIn = false;
            m_pending = false;
            m_engine = null;
            m_socket = socket;
            m_ioThread = ioThread;
            m_hasLingerTimer = false;
            m_identitySent = false;
            m_identityReceived = false;
            m_addr = addr;

            if (options.RawSocket)
            {
                m_identitySent = true;
                m_identityReceived = true;
            }

            m_terminatingPipes = new HashSet<Pipe>();
        }
示例#10
0
文件: Req.cs 项目: ryanjshaw/netmq
 public ReqSession(IOThread ioThread, bool connect,
                   SocketBase socket, Options options,
                   Address addr)
     : base(ioThread, connect, socket, options, addr)
 {
     m_state = State.Identity;
 }
示例#11
0
        public SessionBase(IOThread ioThread, bool connect,
                           SocketBase socket, Options options, Address addr)
            : base(ioThread, options)
        {
            m_ioObject = new IOObject(ioThread);

            m_connect          = connect;
            m_pipe             = null;
            m_incompleteIn     = false;
            m_pending          = false;
            m_engine           = null;
            m_socket           = socket;
            m_ioThread         = ioThread;
            m_hasLingerTimer   = false;
            m_identitySent     = false;
            m_identityReceived = false;
            m_addr             = addr;

            if (options.RawSocket)
            {
                m_identitySent     = true;
                m_identityReceived = true;
            }

            m_terminatingPipes = new HashSet <Pipe>();
        }
示例#12
0
        //  When migrating an object from one I/O thread to another, first
        //  unplug it, then migrate it, then plug it to the new thread.

        public void Plug(IOThread ioThread)
        {
            Debug.Assert(ioThread != null);
            Debug.Assert(m_poller == null);

            //  Retrieve the poller from the thread we are running in.
            m_poller = ioThread.GetPoller();
        }
示例#13
0
 public TcpListener(IOThread ioThread, SocketBase socket, Options options) :
     base(ioThread, options)
 {
     m_ioObject = new IOObject(ioThread);
     m_address  = new TcpAddress();
     m_handle   = null;
     m_socket   = socket;
 }
示例#14
0
        //  When migrating an object from one I/O thread to another, first
        //  unplug it, then migrate it, then plug it to the new thread.
        public void Plug(IOThread ioThread)
        {
            Debug.Assert(ioThread != null);
            Debug.Assert(m_poller == null);

            //  Retrieve the poller from the thread we are running in.
            m_poller = ioThread.GetPoller ();
        }
示例#15
0
 public TcpListener(IOThread ioThread, SocketBase socket, Options options)
     : base(ioThread, options)
 {
     m_ioObject = new IOObject(ioThread);
     m_address = new TcpAddress();
     m_handle = null;
     m_socket = socket;
 }
示例#16
0
        public void Unplug()
        {
            Debug.Assert(m_ioThread != null);

            //  Forget about old poller in preparation to be migrated
            //  to a different I/O thread.
            m_ioThread = null;
            m_handler  = null;
        }
示例#17
0
文件: Own.cs 项目: xuzhe35/netmq
 /// <summary> Initializes a new instance of the <see cref="Own" /> class that is running within I/O thread. </summary>
 /// <param name="ioThread">The I/O thread.</param>
 /// <param name="options">The options.</param>
 /// <remarks> Note that the owner is unspecified in the constructor. It'll be assigned later on using <see cref="SetOwner"/>
 /// when the object is plugged in. </remarks>
 protected Own(IOThread ioThread, Options options)
     : base(ioThread)
 {
     m_options         = options;
     m_terminating     = false;
     m_processedSeqnum = 0;
     m_owner           = null;
     m_termAcks        = 0;
 }
示例#18
0
        public void Plug(IOThread ioThread, SessionBase session)
        {
            m_encoder.SetMsgSource(session);

            AddFd(m_socket);
            SetPollout(m_socket);

            // get the first message from the session because we don't want to send identities
            session.PullMsg();
        }
示例#19
0
 public PgmSender(IOThread ioThread, Options options, Address addr)
     : base(ioThread)
 {
     m_options = options;
     m_addr = addr;
     m_encoder = null;
     m_outBuffer = null;
     m_outBufferSize = 0;
     m_writeSize = 0;
     m_encoder = new Encoder(0, m_options.Endian);
 }
示例#20
0
 public PgmSender(IOThread ioThread, Options options, Address addr)
     : base(ioThread)
 {
     m_options       = options;
     m_addr          = addr;
     m_encoder       = null;
     m_outBuffer     = null;
     m_outBufferSize = 0;
     m_writeSize     = 0;
     m_encoder       = new Encoder(0, m_options.Endian);
 }
示例#21
0
文件: Own.cs 项目: bubbafat/netmq
        //  The object is living within I/O thread.
        public Own(IOThread ioThread, Options options)
            : base(ioThread)
        {
            m_options = options;
            m_terminating = false;
            m_sentSeqnum = new AtomicLong(0);
            m_processedSeqnum = 0;
            m_owner = null;
            m_termAcks = 0;

            owned = new HashSet<Own>();
        }
示例#22
0
        public void InEvent()
        {
            Socket fd;

            try
            {
                fd = Accept();
                Utils.TuneTcpSocket(fd);
                Utils.TuneTcpKeepalives(fd, m_options.TcpKeepalive, m_options.TcpKeepaliveCnt, m_options.TcpKeepaliveIdle, m_options.TcpKeepaliveIntvl);
            }
            catch (NetMQException ex)
            {
                //  If connection was reset by the peer in the meantime, just ignore it.
                //  TODO: Handle specific errors like ENFILE/EMFILE etc.
                //ZError.exc (e);
                m_socket.EventAcceptFailed(m_endpoint, ex.ErrorCode);
                return;
            }


            //  Create the engine object for this connection.
            StreamEngine engine;

            try
            {
                engine = new StreamEngine(fd, m_options, m_endpoint);
            }
            catch (SocketException ex)
            {
                //LOG.error("Failed to initialize StreamEngine", e.getCause());

                ErrorCode errorCode = ErrorHelper.SocketErrorToErrorCode(ex.SocketErrorCode);

                m_socket.EventAcceptFailed(m_endpoint, errorCode);
                throw NetMQException.Create(errorCode);
            }
            //  Choose I/O thread to run connecter in. Given that we are already
            //  running in an I/O thread, there must be at least one available.
            IOThread ioThread = ChooseIOThread(m_options.Affinity);

            //  Create and launch a session object.
            SessionBase session = SessionBase.Create(ioThread, false, m_socket,
                                                     m_options, new Address(m_handle.LocalEndPoint));

            session.IncSeqnum();
            LaunchChild(session);
            SendAttach(session, engine, false);
            m_socket.EventAccepted(m_endpoint, fd);
        }
示例#23
0
        public void Plug(IOThread ioThread, SessionBase session)
        {
            m_session = session;

            m_socket = session.Socket;

            m_ioObject = new IOObject(null);
            m_ioObject.SetHandler(this);
            m_ioObject.Plug(ioThread);
            m_ioObject.AddFd(m_handle);
            m_ioObject.SetPollin(m_handle);

            DropSubscriptions();

            // push message to the session because there is no identity message with pgm
            session.PushMsg(new Msg());
        }
示例#24
0
        public TcpConnecter(IOThread ioThread,
												SessionBase session, Options options,
												Address addr, bool delayedStart)
            : base(ioThread, options)
        {
            m_ioObject = new IOObject(ioThread);
            m_addr = addr;
            m_handle = null;
            m_handleValid = false;
            m_delayedStart = delayedStart;
            m_timerStarted = false;
            m_session = session;
            m_currentReconnectIvl = m_options.ReconnectIvl;

            Debug.Assert(m_addr != null);
            m_endpoint = m_addr.ToString();
            m_socket = session.Socket;
        }
示例#25
0
        public static SessionBase Create([NotNull] IOThread ioThread, bool connect, [NotNull] SocketBase socket, [NotNull] Options options, [NotNull] Address addr)
        {
            switch (options.SocketType)
            {
            case ZmqSocketType.Req:
                return(new Req.ReqSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Dealer:
                return(new Dealer.DealerSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Rep:
                return(new Rep.RepSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Router:
                return(new Router.RouterSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Pub:
                return(new Pub.PubSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Xpub:
                return(new XPub.XPubSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Sub:
                return(new Sub.SubSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Xsub:
                return(new XSub.XSubSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Push:
                return(new Push.PushSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Pull:
                return(new Pull.PullSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Pair:
                return(new Pair.PairSession(ioThread, connect, socket, options, addr));

            case ZmqSocketType.Stream:
                return(new Stream.StreamSession(ioThread, connect, socket, options, addr));

            default:
                throw new InvalidException("SessionBase.Create called with invalid SocketType of " + options.SocketType);
            }
        }
示例#26
0
        public TcpConnecter(IOThread ioThread,
                            SessionBase session, Options options,
                            Address addr, bool delayedStart)
            : base(ioThread, options)
        {
            m_ioObject            = new IOObject(ioThread);
            m_addr                = addr;
            m_handle              = null;
            m_s                   = null;
            m_handleValid         = false;
            m_delayedStart        = delayedStart;
            m_timerStarted        = false;
            m_session             = session;
            m_currentReconnectIvl = m_options.ReconnectIvl;

            Debug.Assert(m_addr != null);
            m_endpoint = m_addr.ToString();
            m_socket   = session.Socket;
        }
示例#27
0
        private void StartConnecting(bool wait)
        {
            Debug.Assert(m_connect);

            //  Choose I/O thread to run connecter in. Given that we are already
            //  running in an I/O thread, there must be at least one available.
            IOThread ioThread = ChooseIOThread(m_options.Affinity);

            Debug.Assert(ioThread != null);

            //  Create the connecter object.

            if (m_addr.Protocol.Equals(Address.TcpProtocol))
            {
                TcpConnecter connecter = new TcpConnecter(
                    ioThread, this, m_options, m_addr, wait);
                //alloc_Debug.Assert(connecter);
                LaunchChild(connecter);
                return;
            }

            if (m_addr.Protocol.Equals(Address.IpcProtocol))
            {
                IpcConnecter connecter = new IpcConnecter(
                    ioThread, this, m_options, m_addr, wait);
                //alloc_Debug.Assert(connecter);
                LaunchChild(connecter);
                return;
            }

            if (m_addr.Protocol.Equals(Address.PgmProtocol) || m_addr.Protocol.Equals(Address.EpgmProtocol))
            {
                PgmSender pgmSender = new PgmSender(m_ioThread, m_options, m_addr);
                pgmSender.Init(m_addr.Resolved as PgmAddress);

                SendAttach(this, pgmSender);

                return;
            }

            Debug.Assert(false);
        }
示例#28
0
        public void Plug(IOThread ioThread, SessionBase session)
        {
            m_encoder.SetMsgSource(session);

            AddFd(m_socket);
            SetPollout(m_socket);

            // get the first message from the session because we don't want to send identities

            Msg msg = new Msg();

            msg.InitEmpty();

            bool ok = session.PullMsg(ref msg);

            if (ok)
            {
                msg.Close();
            }
        }
示例#29
0
        public void InEvent()
        {
            Socket fd;

            try
            {
                fd = Accept();
            }
            catch (SocketException ex)
            {
                m_socket.EventAcceptFailed(m_address.ToString(), ErrorHelper.SocketErrorToErrorCode(ex.SocketErrorCode));
                return;
            }
            catch (NetMQException ex)
            {
                //  If connection was reset by the peer in the meantime, just ignore it.
                //  TODO: Handle specific errors like ENFILE/EMFILE etc.
                //ZError.exc (e);
                m_socket.EventAcceptFailed(m_address.ToString(), ex.ErrorCode);
                return;
            }

            PgmSocket pgmSocket = new PgmSocket(m_options, PgmSocketType.Receiver, m_address);

            pgmSocket.Init(fd);

            PgmSession pgmSession = new PgmSession(pgmSocket, m_options);

            IOThread ioThread = ChooseIOThread(m_options.Affinity);

            SessionBase session = SessionBase.Create(ioThread, false, m_socket,
                                                     m_options, new Address(m_handle.LocalEndPoint));

            session.IncSeqnum();
            LaunchChild(session);
            SendAttach(session, pgmSession, false);
            m_socket.EventAccepted(m_address.ToString(), fd);
        }
示例#30
0
        public void Connect([NotNull] string addr)
        {
            CheckContextTerminated();

            //  Process pending commands, if any.
            ProcessCommands(0, false);

            string address;
            string protocol;

            DecodeAddress(addr, out address, out protocol);

            CheckProtocol(protocol);

            if (protocol.Equals(Address.InProcProtocol))
            {
                //  TODO: inproc connect is specific with respect to creating pipes
                //  as there's no 'reconnect' functionality implemented. Once that
                //  is in place we should follow generic pipe creation algorithm.

                //  Find the peer endpoint.
                Ctx.Endpoint peer = FindEndpoint(addr);

                // The total HWM for an inproc connection should be the sum of
                // the binder's HWM and the connector's HWM.
                int sndhwm;
                int rcvhwm;
                if (m_options.SendHighWatermark == 0 || peer.Options.ReceiveHighWatermark == 0)
                {
                    sndhwm = 0;
                }
                else
                {
                    sndhwm = m_options.SendHighWatermark + peer.Options.ReceiveHighWatermark;
                }
                if (m_options.ReceiveHighWatermark == 0 || peer.Options.SendHighWatermark == 0)
                {
                    rcvhwm = 0;
                }
                else
                {
                    rcvhwm = m_options.ReceiveHighWatermark + peer.Options.SendHighWatermark;
                }

                //  Create a bi-directional pipe to connect the peers.
                ZObject[] parents        = { this, peer.Socket };
                int[]     highWaterMarks = { sndhwm, rcvhwm };
                bool[]    delays         = { m_options.DelayOnDisconnect, m_options.DelayOnClose };
                Pipe[]    pipes          = Pipe.PipePair(parents, highWaterMarks, delays);

                //  Attach local end of the pipe to this socket object.
                AttachPipe(pipes[0]);

                //  If required, send the identity of the peer to the local socket.
                if (peer.Options.RecvIdentity)
                {
                    var id = new Msg();
                    id.InitPool(peer.Options.IdentitySize);
                    id.Put(peer.Options.Identity, 0, peer.Options.IdentitySize);
                    id.SetFlags(MsgFlags.Identity);
                    bool written = pipes[0].Write(ref id);
                    Debug.Assert(written);
                    pipes[0].Flush();
                }

                //  If required, send the identity of the local socket to the peer.
                if (m_options.RecvIdentity)
                {
                    var id = new Msg();
                    id.InitPool(m_options.IdentitySize);
                    id.Put(m_options.Identity, 0, m_options.IdentitySize);
                    id.SetFlags(MsgFlags.Identity);
                    bool written = pipes[1].Write(ref id);
                    Debug.Assert(written);
                    pipes[1].Flush();
                }

                //  Attach remote end of the pipe to the peer socket. Note that peer's
                //  seqnum was incremented in find_endpoint function. We don't need it
                //  increased here.
                SendBind(peer.Socket, pipes[1], false);

                // Save last endpoint URI
                m_options.LastEndpoint = addr;

                // remember inproc connections for disconnect
                m_inprocs.Add(addr, pipes[0]);

                return;
            }

            //  Choose the I/O thread to run the session in.
            IOThread ioThread = ChooseIOThread(m_options.Affinity);

            if (ioThread == null)
            {
                throw NetMQException.Create("Empty IO Thread", ErrorCode.EmptyThread);
            }
            var paddr = new Address(protocol, address);

            //  Resolve address (if needed by the protocol)
            if (protocol.Equals(Address.TcpProtocol))
            {
                paddr.Resolved = (new TcpAddress());
                paddr.Resolved.Resolve(
                    address, m_options.IPv4Only);
            }
            else if (protocol.Equals(Address.IpcProtocol))
            {
                paddr.Resolved = (new IpcAddress());
                paddr.Resolved.Resolve(address, true);
            }
            else if (protocol.Equals(Address.PgmProtocol) || protocol.Equals(Address.EpgmProtocol))
            {
                if (m_options.SocketType == ZmqSocketType.Sub || m_options.SocketType == ZmqSocketType.Xsub)
                {
                    Bind(addr);
                    return;
                }

                paddr.Resolved = new PgmAddress();
                paddr.Resolved.Resolve(address, m_options.IPv4Only);
            }

            //  Create session.
            SessionBase session = SessionBase.Create(ioThread, true, this, m_options, paddr);

            Debug.Assert(session != null);

            //  PGM does not support subscription forwarding; ask for all data to be
            //  sent to this pipe.
            bool icanhasall = protocol.Equals(Address.PgmProtocol) || protocol.Equals(Address.EpgmProtocol);

            if (!m_options.DelayAttachOnConnect || icanhasall)
            {
                //  Create a bi-directional pipe.
                ZObject[] parents = { this, session };
                int[]     hwms    = { m_options.SendHighWatermark, m_options.ReceiveHighWatermark };
                bool[]    delays  = { m_options.DelayOnDisconnect, m_options.DelayOnClose };
                Pipe[]    pipes   = Pipe.PipePair(parents, hwms, delays);

                //  Attach local end of the pipe to the socket object.
                AttachPipe(pipes[0], icanhasall);

                //  Attach remote end of the pipe to the session object later on.
                session.AttachPipe(pipes[1]);
            }

            // Save last endpoint URI
            m_options.LastEndpoint = paddr.ToString();

            AddEndpoint(addr, session);
        }
示例#31
0
        public void Bind(String addr)
        {
            CheckContextTerminated();

            //  Process pending commands, if any.
            ProcessCommands(0, false);

            string protocol;
            string address;

            DecodeAddress(addr, out address, out protocol);

            CheckProtocol(protocol);

            if (protocol.Equals(Address.InProcProtocol))
            {
                Ctx.Endpoint endpoint = new Ctx.Endpoint(this, m_options);

                bool addressRegistered = RegisterEndpoint(addr, endpoint);

                if (!addressRegistered)
                {
                    throw new AddressAlreadyInUseException("Cannot bind address, address already in use");
                }

                // Save last endpoint URI
                m_options.LastEndpoint = addr;

                return;
            }
            if ((protocol.Equals(Address.PgmProtocol) || protocol.Equals(Address.EpgmProtocol)) && (
                    m_options.SocketType == ZmqSocketType.Pub || m_options.SocketType == ZmqSocketType.Xpub))
            {
                //  For convenience's sake, bind can be used interchageable with
                //  connect for PGM and EPGM transports.
                Connect(addr);
                return;
            }

            //  Remaining trasnports require to be run in an I/O thread, so at this
            //  point we'll choose one.
            IOThread ioThread = ChooseIOThread(m_options.Affinity);

            if (ioThread == null)
            {
                throw NetMQException.Create(ErrorCode.EmptyThread);
            }

            if (protocol.Equals(Address.TcpProtocol))
            {
                TcpListener listener = new TcpListener(
                    ioThread, this, m_options);

                try
                {
                    listener.SetAddress(address);
                    m_port = listener.Port;
                }
                catch (NetMQException ex)
                {
                    listener.Destroy();
                    EventBindFailed(addr, ex.ErrorCode);

                    throw;
                }

                // Save last endpoint URI
                m_options.LastEndpoint = listener.Address;

                AddEndpoint(addr, listener);

                return;
            }

            if (protocol.Equals(Address.PgmProtocol) || protocol.Equals(Address.EpgmProtocol))
            {
                PgmListener listener = new PgmListener(ioThread, this, m_options);

                try
                {
                    listener.Init(address);
                }
                catch (NetMQException ex)
                {
                    listener.Destroy();
                    EventBindFailed(addr, ex.ErrorCode);

                    throw;
                }

                m_options.LastEndpoint = addr;

                AddEndpoint(addr, listener);

                return;
            }

            if (protocol.Equals(Address.IpcProtocol))
            {
                IpcListener listener = new IpcListener(
                    ioThread, this, m_options);

                try
                {
                    listener.SetAddress(address);
                    m_port = listener.Port;
                }
                catch (NetMQException ex)
                {
                    listener.Destroy();
                    EventBindFailed(addr, ex.ErrorCode);

                    throw;
                }

                // Save last endpoint URI
                m_options.LastEndpoint = listener.Address;

                AddEndpoint(addr, listener);
                return;
            }

            Debug.Assert(false);
            throw new FaultException();
        }
示例#32
0
        /// <summary>
        /// "Un-Plug" this IOObject from it's current IOThread, and set it's handler to null.
        /// </summary>
        /// <remarks>
        /// When migrating an object from one I/O thread to another, first
        /// unplug it, then migrate it, then plug it to the new thread.
        /// </remarks>
        public void Unplug()
        {
            Debug.Assert(m_ioThread != null);

            //  Forget about old poller in preparation to be migrated
            //  to a different I/O thread.
            m_ioThread = null;
            m_handler = null;
        }
示例#33
0
        /// <summary>
        /// "Plug in" this IOObject to the given IOThread, - ie associate this with the specified IOThread.
        /// </summary>
        /// <param name="ioThread">the IOThread for this object to live in</param>
        /// <remarks>
        /// When migrating an object from one I/O thread to another, first
        /// unplug it, then migrate it, then plug it to the new thread.
        /// </remarks>
        public void Plug([NotNull] IOThread ioThread)
        {
            Debug.Assert(ioThread != null);

            m_ioThread = ioThread;
        }
示例#34
0
            public ReqSession(IOThread ioThread, bool connect,
												SocketBase socket, Options options,
												Address addr)
                : base(ioThread, connect, socket, options, addr)
            {
                m_state = State.Identity;
            }
示例#35
0
        public void Plug(IOThread ioThread, SessionBase session)
        {
            m_session = session;

            m_socket = session.Socket;

            m_ioObject = new IOObject(null);
            m_ioObject.SetHandler(this);
            m_ioObject.Plug(ioThread);
            m_ioObject.AddFd(m_handle);
            m_ioObject.SetPollin(m_handle);

            DropSubscriptions();

            // push message to the session because there is no identity message with pgm
            session.PushMsg(new Msg());
        }
示例#36
0
        public void Bind(String addr)
        {
            if (m_ctxTerminated)
            {
                throw TerminatingException.Create();
            }

            //  Process pending commands, if any.
            ProcessCommands(0, false);

            string protocol;
            string address;

            DecodeAddress(addr, out address, out protocol);

            CheckProtocol(protocol);

            if (protocol.Equals("inproc"))
            {
                Ctx.Endpoint endpoint = new Ctx.Endpoint(this, m_options);

                RegisterEndpoint(addr, endpoint);

                // Save last endpoint URI
                m_options.LastEndpoint = addr;

                return;
            }
            if ((protocol.Equals("pgm") || protocol.Equals("epgm")) && (
                    m_options.SocketType == ZmqSocketType.Pub || m_options.SocketType == ZmqSocketType.Xpub))
            {
                //  For convenience's sake, bind can be used interchageable with
                //  connect for PGM and EPGM transports.
                Connect(addr);
                return;
            }

            //  Remaining trasnports require to be run in an I/O thread, so at this
            //  point we'll choose one.
            IOThread ioThread = ChooseIOThread(m_options.Affinity);

            if (ioThread == null)
            {
                throw NetMQException.Create(ErrorCode.EMTHREAD);
            }

            if (protocol.Equals("tcp"))
            {
                TcpListener listener = new TcpListener(
                    ioThread, this, m_options);

                try
                {
                    listener.SetAddress(address);
                }
                catch (NetMQException ex)
                {
                    listener.Destroy();
                    EventBindFailed(addr, ex.ErrorCode);

                    throw;
                }

                // Save last endpoint URI
                m_options.LastEndpoint = listener.Address;

                AddEndpoint(addr, listener);

                return;
            }

            if (protocol.Equals("pgm") || protocol.Equals("epgm"))
            {
                PgmListener listener = new PgmListener(ioThread, this, m_options);

                try
                {
                    listener.Init(address);
                }
                catch (NetMQException ex)
                {
                    listener.Destroy();
                    EventBindFailed(addr, ex.ErrorCode);

                    throw;
                }

                m_options.LastEndpoint = addr;

                AddEndpoint(addr, listener);

                return;
            }

            if (protocol.Equals("ipc"))
            {
                IpcListener listener = new IpcListener(
                    ioThread, this, m_options);

                try
                {
                    listener.SetAddress(address);
                }
                catch (NetMQException ex)
                {
                    listener.Destroy();
                    EventBindFailed(addr, ex.ErrorCode);

                    throw;
                }

                // Save last endpoint URI
                m_options.LastEndpoint = listener.Address;

                AddEndpoint(addr, listener);
                return;
            }

            Debug.Assert(false);
            throw NetMQException.Create(ErrorCode.EFAULT);
        }
示例#37
0
        public void Plug(IOThread ioThread, SessionBase session)
        {
            m_encoder.SetMsgSource(session);

            AddFd(m_socket);
            SetPollout(m_socket);

            // get the first message from the session because we don't want to send identities
            session.PullMsg();
        }
示例#38
0
        public static SessionBase Create(IOThread ioThread, bool connect,
                                                                         SocketBase socket, Options options, Address addr)
        {
            SessionBase s;
            switch (options.SocketType)
            {
                case ZmqSocketType.Req:
                    s = new Req.ReqSession(ioThread, connect,
                                                                     socket, options, addr);
                    break;
                case ZmqSocketType.Dealer:
                    s = new Dealer.DealerSession(ioThread, connect,
                                                                                socket, options, addr);
                    break;
                case ZmqSocketType.Rep:
                    s = new Rep.RepSession(ioThread, connect,
                                                                    socket, options, addr);
                    break;
                case ZmqSocketType.Router:
                    s = new Router.RouterSession(ioThread, connect,
                                                                                socket, options, addr);
                    break;
                case ZmqSocketType.Pub:
                    s = new Pub.PubSession(ioThread, connect,
                                                                    socket, options, addr);
                    break;
                case ZmqSocketType.Xpub:
                    s = new XPub.XPubSession(ioThread, connect,
                                                                     socket, options, addr);
                    break;
                case ZmqSocketType.Sub:
                    s = new Sub.SubSession(ioThread, connect,
                                                                     socket, options, addr);
                    break;
                case ZmqSocketType.Xsub:
                    s = new XSub.XSubSession(ioThread, connect,
                                                                        socket, options, addr);
                    break;

                case ZmqSocketType.Push:
                    s = new Push.PushSession(ioThread, connect,
                                                                        socket, options, addr);
                    break;
                case ZmqSocketType.Pull:
                    s = new Pull.PullSession(ioThread, connect,
                                                                        socket, options, addr);
                    break;
                case ZmqSocketType.Pair:
                    s = new Pair.PairSession(ioThread, connect,
                                                                        socket, options, addr);
                    break;
                case ZmqSocketType.Stream:
                    s = new Stream.StreamSession(ioThread, connect, socket, options, addr);
                    break;
                default:
                    throw InvalidException.Create("type=" + options.SocketType);

            }
            return s;
        }
示例#39
0
 public IpcListener(IOThread ioThread, SocketBase socket, Options options) : base(ioThread, socket, options)
 {
     m_address = new IpcAddress();
 }
示例#40
0
        //  When migrating an object from one I/O thread to another, first
        //  unplug it, then migrate it, then plug it to the new thread.

        public void Plug([NotNull] IOThread ioThread)
        {
            Debug.Assert(ioThread != null);

            m_ioThread = ioThread;
        }
示例#41
0
 public IpcListener(IOThread ioThread, SocketBase socket, Options options)
     : base(ioThread, socket, options)
 {
     m_address = new IpcAddress();
 }
示例#42
0
        public SocketBase CreateSocket(ZmqSocketType type)
        {
            SocketBase s = null;

            lock (m_slotSync)
            {
                if (m_starting)
                {
                    m_starting = false;
                    //  Initialise the array of mailboxes. Additional three slots are for
                    //  zmq_term thread and reaper thread.

                    int ios;
                    int mazmq;

                    lock (m_optSync)
                    {
                        mazmq = m_maxSockets;
                        ios   = m_ioThreadCount;
                    }
                    m_slotCount = mazmq + ios + 2;
                    m_slots     = new Mailbox[m_slotCount];
                    //alloc_Debug.Assert(slots);

                    //  Initialise the infrastructure for zmq_term thread.
                    m_slots[TermTid] = m_termMailbox;

                    //  Create the reaper thread.
                    m_reaper = new Reaper(this, ReaperTid);
                    //alloc_Debug.Assert(reaper);
                    m_slots[ReaperTid] = m_reaper.Mailbox;
                    m_reaper.Start();

                    //  Create I/O thread objects and launch them.
                    for (int i = 2; i != ios + 2; i++)
                    {
                        IOThread ioThread = new IOThread(this, i);
                        //alloc_Debug.Assert(io_thread);
                        m_ioThreads.Add(ioThread);
                        m_slots[i] = ioThread.Mailbox;
                        ioThread.Start();
                    }

                    //  In the unused part of the slot array, create a list of empty slots.
                    for (int i = (int)m_slotCount - 1;
                         i >= (int)ios + 2; i--)
                    {
                        m_emptySlots.Push(i);
                        m_slots[i] = null;
                    }
                }

                //  Once zmq_term() was called, we can't create new sockets.
                if (m_terminating)
                {
                    throw TerminatingException.Create();
                }

                //  If max_sockets limit was reached, return error.
                if (m_emptySlots.Count == 0)
                {
                    throw NetMQException.Create(ErrorCode.EMFILE);
                }

                //  Choose a slot for the socket.
                int slot = m_emptySlots.Pop();

                //  Generate new unique socket ID.
                int sid = Interlocked.Increment(ref s_maxSocketId);

                //  Create the socket and register its mailbox.
                s = SocketBase.Create(type, this, slot, sid);
                if (s == null)
                {
                    m_emptySlots.Push(slot);
                    return(null);
                }
                m_sockets.Add(s);
                m_slots[slot] = s.Mailbox;

                //LOG.debug("NEW Slot [" + slot + "] " + s);
            }

            return(s);
        }
示例#43
0
文件: Ctx.cs 项目: wxl-007/ShadowDota
        public SocketBase CreateSocket(ZmqSocketType type)
        {
            lock (m_slotSync)
            {
                if (m_starting)
                {
                    m_starting = false;
                    //  Initialise the array of mailboxes. Additional three slots are for
                    //  zmq_term thread and reaper thread.

                    int ios;
                    int mazmq;

                    lock (m_optSync)
                    {
                        mazmq = m_maxSockets;
                        ios   = m_ioThreadCount;
                    }
                    m_slotCount = mazmq + ios + 2;
                    m_slots     = new IMailbox[m_slotCount];
                    //alloc_Debug.Assert(slots);

                    //  Initialise the infrastructure for zmq_term thread.
                    m_slots[TermTid] = m_termMailbox;

                    //  Create the reaper thread.
                    m_reaper = new Reaper(this, ReaperTid);
                    //alloc_Debug.Assert(reaper);
                    m_slots[ReaperTid] = m_reaper.Mailbox;
                    m_reaper.Start();

                    //  Create I/O thread objects and launch them.
                    for (int i = 2; i != ios + 2; i++)
                    {
                        var ioThread = new IOThread(this, i);
                        //alloc_Debug.Assert(io_thread);
                        m_ioThreads.Add(ioThread);
                        m_slots[i] = ioThread.Mailbox;
                        ioThread.Start();
                    }

                    //  In the unused part of the slot array, create a list of empty slots.
                    for (int i = m_slotCount - 1; i >= ios + 2; i--)
                    {
                        m_emptySlots.Push(i);
                        m_slots[i] = null;
                    }
                }

                //  Once zmq_term() was called, we can't create new sockets.
                if (m_terminating)
                {
                    string xMsg = String.Format("Ctx.CreateSocket({0}), cannot create new socket while terminating.", type);
                    throw new TerminatingException(innerException: null, message: xMsg);
                }

                //  If max_sockets limit was reached, return error.
                if (m_emptySlots.Count == 0)
                {
#if DEBUG
                    string xMsg = String.Format("Ctx.CreateSocket({0}), max number of sockets {1} reached.", type, m_maxSockets);
                    throw NetMQException.Create(xMsg, ErrorCode.TooManyOpenSockets);
#else
                    throw NetMQException.Create(ErrorCode.TooManyOpenSockets);
#endif
                }

                //  Choose a slot for the socket.
                int slot = m_emptySlots.Pop();

                //  Generate new unique socket ID.
                int socketId = Interlocked.Increment(ref s_maxSocketId);

                //  Create the socket and register its mailbox.
                SocketBase s = SocketBase.Create(type, this, slot, socketId);

                m_sockets.Add(s);
                m_slots[slot] = s.Mailbox;

                //LOG.debug("NEW Slot [" + slot + "] " + s);

                return(s);
            }
        }
示例#44
0
        public SocketBase CreateSocket(ZmqSocketType type)
        {
            SocketBase s = null;
            lock (m_slotSync)
            {
                if (m_starting)
                {

                    m_starting = false;
                    //  Initialise the array of mailboxes. Additional three slots are for
                    //  zmq_term thread and reaper thread.

                    int ios;
                    int mazmq;

                    lock (m_optSync)
                    {
                        mazmq = m_maxSockets;
                        ios = m_ioThreadCount;
                    }
                    m_slotCount = mazmq + ios + 2;
                    m_slots = new Mailbox[m_slotCount];
                    //alloc_Debug.Assert(slots);

                    //  Initialise the infrastructure for zmq_term thread.
                    m_slots[TermTid] = m_termMailbox;

                    //  Create the reaper thread.
                    m_reaper = new Reaper(this, ReaperTid);
                    //alloc_Debug.Assert(reaper);
                    m_slots[ReaperTid] = m_reaper.Mailbox;
                    m_reaper.Start();

                    //  Create I/O thread objects and launch them.
                    for (int i = 2; i != ios + 2; i++)
                    {
                        IOThread ioThread = new IOThread(this, i);
                        //alloc_Debug.Assert(io_thread);
                        m_ioThreads.Add(ioThread);
                        m_slots[i] = ioThread.Mailbox;
                        ioThread.Start();
                    }

                    //  In the unused part of the slot array, create a list of empty slots.
                    for (int i = (int)m_slotCount - 1;
                         i >= (int)ios + 2; i--)
                    {
                        m_emptySlots.Push(i);
                        m_slots[i] = null;
                    }

                }

                //  Once zmq_term() was called, we can't create new sockets.
                if (m_terminating)
                {
                    ZError.ErrorNumber = ErrorNumber.ETERM;
                    return null;
                }

                //  If max_sockets limit was reached, return error.
                if (m_emptySlots.Count == 0)
                {
                    ZError.ErrorNumber = ErrorNumber.EMFILE;
                    return null;
                }

                //  Choose a slot for the socket.
                int slot = m_emptySlots.Pop();

                //  Generate new unique socket ID.
                int sid = s_maxSocketId.IncrementAndGet();

                //  Create the socket and register its mailbox.
                s = SocketBase.Create(type, this, slot, sid);
                if (s == null)
                {
                    m_emptySlots.Push(slot);
                    return null;
                }
                m_sockets.Add(s);
                m_slots[slot] = s.Mailbox;

                //LOG.debug("NEW Slot [" + slot + "] " + s);
            }

            return s;
        }
示例#45
0
        public void Plug(IOThread ioThread,
		                 SessionBase session)
        {
            Debug.Assert(!m_plugged);
            m_plugged = true;

            //  Connect to session object.
            Debug.Assert(m_session == null);
            Debug.Assert(session != null);
            m_session = session;
            m_socket = m_session.Socket;

            m_ioObject = new IOObject(null);
            m_ioObject.SetHandler(this);
            //  Connect to I/O threads poller object.
            m_ioObject.Plug(ioThread);
            m_ioObject.AddFd(m_handle);

            //  Send the 'length' and 'flags' fields of the identity message.
            //  The 'length' field is encoded in the long format.

            m_greetingOutputBuffer[m_outsize++] = ((byte) 0xff);
            m_greetingOutputBuffer.PutLong((long) m_options.IdentitySize + 1, 1);
            m_outsize += 8;
            m_greetingOutputBuffer[m_outsize++] = ((byte) 0x7f);

            m_outpos = new ByteArraySegment(m_greetingOutputBuffer);

            m_ioObject.SetPollin(m_handle);
            m_ioObject.SetPollout(m_handle);

            //  Flush all the data that may have been already received downstream.
            InEvent();
        }
示例#46
0
        public SocketBase CreateSocket(ZmqSocketType type)
        {
            lock (m_slotSync)
            {
                if (m_starting)
                {
                    m_starting = false;
                    //  Initialise the array of mailboxes. Additional three slots are for
                    //  zmq_term thread and reaper thread.

                    int ios;
                    int mazmq;

                    lock (m_optSync)
                    {
                        mazmq = m_maxSockets;
                        ios = m_ioThreadCount;
                    }
                    m_slotCount = mazmq + ios + 2;
                    m_slots = new IMailbox[m_slotCount];
                    //alloc_Debug.Assert(slots);

                    //  Initialise the infrastructure for zmq_term thread.
                    m_slots[TermTid] = m_termMailbox;

                    //  Create the reaper thread.
                    m_reaper = new Reaper(this, ReaperTid);
                    //alloc_Debug.Assert(reaper);
                    m_slots[ReaperTid] = m_reaper.Mailbox;
                    m_reaper.Start();

                    //  Create I/O thread objects and launch them.
                    for (int i = 2; i != ios + 2; i++)
                    {
                        var ioThread = new IOThread(this, i);
                        //alloc_Debug.Assert(io_thread);
                        m_ioThreads.Add(ioThread);
                        m_slots[i] = ioThread.Mailbox;
                        ioThread.Start();
                    }

                    //  In the unused part of the slot array, create a list of empty slots.
                    for (int i = m_slotCount - 1; i >= ios + 2; i--)
                    {
                        m_emptySlots.Push(i);
                        m_slots[i] = null;
                    }
                }

                //  Once zmq_term() was called, we can't create new sockets.
                if (m_terminating)
                {
                    string xMsg = string.Format("Ctx.CreateSocket({0}), cannot create new socket while terminating.", type);
                    throw new TerminatingException(innerException: null, message: xMsg);
                }

                //  If max_sockets limit was reached, return error.
                if (m_emptySlots.Count == 0)
                {
            #if DEBUG
                    string xMsg = string.Format("Ctx.CreateSocket({0}), max number of sockets {1} reached.", type, m_maxSockets);
                    throw NetMQException.Create(xMsg, ErrorCode.TooManyOpenSockets);
            #else
                    throw NetMQException.Create(ErrorCode.TooManyOpenSockets);
            #endif
                }

                //  Choose a slot for the socket.
                int slot = m_emptySlots.Pop();

                //  Generate new unique socket ID.
                int socketId = Interlocked.Increment(ref s_maxSocketId);

                //  Create the socket and register its mailbox.
                SocketBase s = SocketBase.Create(type, this, slot, socketId);

                m_sockets.Add(s);
                m_slots[slot] = s.Mailbox;

                //LOG.debug("NEW Slot [" + slot + "] " + s);

                return s;
            }
        }
示例#47
0
文件: Sub.cs 项目: wbj808178/netmq
 public SubSession(IOThread ioThread, bool connect,
                   SocketBase socket, Options options, Address addr)
     : base(ioThread, connect, socket, options, addr)
 {
 }
示例#48
0
        public void Bind([NotNull] string addr)
        {
            CheckContextTerminated();

            //  Process pending commands, if any.
            ProcessCommands(0, false);

            string protocol;
            string address;

            DecodeAddress(addr, out address, out protocol);

            CheckProtocol(protocol);

            if (protocol.Equals(Address.InProcProtocol))
            {
                var endpoint = new Ctx.Endpoint(this, m_options);

                bool addressRegistered = RegisterEndpoint(addr, endpoint);

                if (!addressRegistered)
                {
                    string xMsg = String.Format("Cannot bind address ( {0} ) - already in use.", addr);
                    throw new AddressAlreadyInUseException(xMsg);
                }

                // Save last endpoint URI
                m_options.LastEndpoint = addr;

                return;
            }
            if ((protocol.Equals(Address.PgmProtocol) || protocol.Equals(Address.EpgmProtocol)) && (
                    m_options.SocketType == ZmqSocketType.Pub || m_options.SocketType == ZmqSocketType.Xpub))
            {
                //  For convenience's sake, bind can be used interchangeable with
                //  connect for PGM and EPGM transports.
                Connect(addr);
                return;
            }

            //  Remaining transports require to be run in an I/O thread, so at this
            //  point we'll choose one.
            IOThread ioThread = ChooseIOThread(m_options.Affinity);

            if (ioThread == null)
            {
                throw NetMQException.Create(ErrorCode.EmptyThread);
            }

            if (protocol.Equals(Address.TcpProtocol))
            {
                var listener = new TcpListener(ioThread, this, m_options);

                try
                {
                    listener.SetAddress(address);
                    m_port = listener.Port;

                    // Recreate the address string (localhost:1234) in case the port was system-assigned
                    var host = address.Substring(0, address.IndexOf(':'));
                    addr = "tcp://" + host + ":" + m_port;
                }
                catch (NetMQException ex)
                {
                    listener.Destroy();
                    EventBindFailed(addr, ex.ErrorCode);

                    throw;
                }

                // Save last endpoint URI
                m_options.LastEndpoint = listener.Address;

                AddEndpoint(addr, listener);

                return;
            }

            if (protocol.Equals(Address.PgmProtocol) || protocol.Equals(Address.EpgmProtocol))
            {
                var listener = new PgmListener(ioThread, this, m_options);

                try
                {
                    listener.Init(address);
                }
                catch (NetMQException ex)
                {
                    listener.Destroy();
                    EventBindFailed(addr, ex.ErrorCode);

                    throw;
                }

                m_options.LastEndpoint = addr;

                AddEndpoint(addr, listener);

                return;
            }

            if (protocol.Equals(Address.IpcProtocol))
            {
                var listener = new IpcListener(ioThread, this, m_options);

                try
                {
                    listener.SetAddress(address);
                    m_port = listener.Port;
                }
                catch (NetMQException ex)
                {
                    listener.Destroy();
                    EventBindFailed(addr, ex.ErrorCode);

                    throw;
                }

                // Save last endpoint URI
                m_options.LastEndpoint = listener.Address;

                AddEndpoint(addr, listener);
                return;
            }

            Debug.Assert(false);
            throw new FaultException(String.Format("SocketBase.Bind({0}) failure.", addr));
        }
示例#49
0
            public PairSession(IOThread ioThread, bool connect,
			                   SocketBase socket, Options options,
			                   Address addr)
                : base(ioThread, connect, socket, options, addr)
            {
            }
示例#50
0
文件: Own.cs 项目: JayShelton/netmq
 /// <summary> Initializes a new instance of the <see cref="Own" /> class that is running within I/O thread. </summary>
 /// <param name="ioThread">The I/O thread.</param>
 /// <param name="options">The options.</param>
 /// <remarks> Note that the owner is unspecified in the constructor. It'll be assigned later on using <see cref="SetOwner"/>
 /// when the object is plugged in. </remarks>
 protected Own(IOThread ioThread, Options options)
     : base(ioThread)
 {
     m_options = options;
     m_terminating = false;
     m_processedSeqnum = 0;
     m_owner = null;
     m_termAcks = 0;
 }