示例#1
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);
        }
示例#2
0
        public void InCompleted(SocketError socketError, int bytesTransferred)
        {
            if (socketError != SocketError.Success)
            {
                if (socketError == SocketError.ConnectionReset || socketError == SocketError.NoBufferSpaceAvailable ||
                    socketError == SocketError.TooManyOpenSockets)
                {
                    m_socket.EventAcceptFailed(m_endpoint, ErrorHelper.SocketErrorToErrorCode(socketError));

                    Accept();
                }
                else
                {
                    m_acceptedSocket.Dispose();

                    NetMQException exception = NetMQException.Create(socketError);

                    m_socket.EventAcceptFailed(m_endpoint, exception.ErrorCode);
                    throw exception;
                }
            }
            else
            {
                // TODO: check TcpFilters

                m_acceptedSocket.NoDelay = true;

                // Utils.TuneTcpKeepalives(m_acceptedSocket, m_options.TcpKeepalive, m_options.TcpKeepaliveCnt, m_options.TcpKeepaliveIdle, m_options.TcpKeepaliveIntvl);

                //  Create the engine object for this connection.
                StreamEngine engine = new StreamEngine(m_acceptedSocket, m_options, m_endpoint);

                //  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.
                // TODO: send null in address parameter, is unneed in this case
                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, m_acceptedSocket);

                Accept();
            }
        }
示例#3
0
        /// <summary>
        /// Set address to listen on.
        /// </summary>
        /// <param name="addr">a string denoting the address to set this to</param>
        public virtual void SetAddress(string addr)
        {
            m_address.Resolve(addr, m_options.IPv4Only);

            Assumes.NotNull(m_address.Address);
            Assumes.NotNull(m_handle);

            try
            {
                m_handle = AsyncSocket.Create(m_address.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                if (!m_options.IPv4Only && m_address.Address.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    try
                    {
                        // This is not supported on old windows operating systems and might throw exception
                        m_handle.SetSocketOption(SocketOptionLevel.IPv6, IPv6Only, 0);
                    }
                    catch
                    {
                    }
                }

#if NETSTANDARD2_0 || NETSTANDARD2_1
                // This command is failing on linux
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    m_handle.ExclusiveAddressUse = false;
                }
#else
                m_handle.ExclusiveAddressUse = false;
#endif
                m_handle.Bind(m_address.Address);
                m_handle.Listen(m_options.Backlog);

                // Copy the port number after binding in case we requested a system-allocated port number (TCP port zero)
                m_address.Address.Port = m_handle.LocalEndPoint.Port;
                m_endpoint             = m_address.ToString();

                m_socket.EventListening(m_endpoint, m_handle);

                m_port = m_handle.LocalEndPoint.Port;
            }
            catch (SocketException ex)
            {
                Close();
                throw NetMQException.Create(ex);
            }
        }
示例#4
0
        public int BindRandomPort(String addr)
        {
            string address, protocol;

            DecodeAddress(addr, out address, out protocol);
            if (protocol.Equals(Address.TcpProtocol))
            {
                Bind(addr + ":0");
                return(m_port);
            }
            else
            {
                throw NetMQException.Create(ErrorCode.EINVAL);
            }
        }
示例#5
0
        /// <summary>
        ///     Set address to listen on.
        /// </summary>
        /// <param name="addr">a string denoting the address to set this to</param>
        public virtual void SetAddress([NotNull] string addr)
        {
            this.m_address.Resolve(addr, this.m_options.IPv4Only);

            try
            {
                this.m_handle = AsyncSocket.Create(this.m_address.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                Debug.Assert(this.m_handle != null);

                if (!this.m_options.IPv4Only && this.m_address.Address.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    try
                    {
                        // This is not supported on old windows operation system and might throw exception
                        this.m_handle.SetSocketOption(SocketOptionLevel.IPv6, TcpListener.IPv6Only, 0);
                    }
                    catch
                    {
                    }
                }

                #if NETSTANDARD1_3
                // This command is failing on linux
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    m_handle.ExclusiveAddressUse = false;
                }
                                #else
                this.m_handle.ExclusiveAddressUse = false;
                #endif
                this.m_handle.Bind(this.m_address.Address);
                this.m_handle.Listen(this.m_options.Backlog);

                // Copy the port number after binding in case we requested a system-allocated port number (TCP port zero)
                this.m_address.Address.Port = this.m_handle.LocalEndPoint.Port;
                this.m_endpoint             = this.m_address.ToString();

                this.m_socket.EventListening(this.m_endpoint, this.m_handle);

                this.m_port = this.m_handle.LocalEndPoint.Port;
            }
            catch (SocketException ex)
            {
                this.Close();
                throw NetMQException.Create(ex);
            }
        }
示例#6
0
        //  Management of inproc endpoints.
        public void RegisterEndpoint(String addr, Endpoint endpoint)
        {
            bool exist;

            lock (m_endpointsSync)
            {
                exist = m_endpoints.ContainsKey(addr);

                m_endpoints[addr] = endpoint;
            }

            if (exist)
            {
                throw NetMQException.Create(ErrorCode.EADDRINUSE);
            }
        }
        public void Run(PairSocket shim, object[] args, CancellationToken token)
        {
            if (args == null || args.Count() != 1)
            {
                throw new InvalidOperationException(
                          "Args were not correct, expected one argument");
            }

            AccountAction accountAction = JsonConvert.DeserializeObject <AccountAction>(args[0].ToString());


            while (!token.IsCancellationRequested)
            {
                //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 "AMEND ACCOUNT"
                NetMQMessage msg = null;

                //this may throw NetMQException if we have disposed of the actor
                //end of the pipe, and the CancellationToken.IsCancellationRequested
                //did not get picked up this loop cycle
                msg = shim.ReceiveMessage();

                if (msg == null)
                {
                    break;
                }

                if (msg[0].ConvertToString() == "AMEND ACCOUNT")
                {
                    string  json    = msg[1].ConvertToString();
                    Account account = JsonConvert.DeserializeObject <Account>(json);
                    AmmendAccount(accountAction, account);
                    shim.Send(JsonConvert.SerializeObject(account));
                }
                else
                {
                    throw NetMQException.Create("Unexpected command",
                                                ErrorCode.EFAULT);
                }
            }
        }
示例#8
0
        // Send multiple messages.
        //
        // If flag bit ZMQ_SNDMORE is set the vector is treated as
        // a single multi-part message, i.e. the last message has
        // ZMQ_SNDMORE bit switched off.
        //
        public void SendIOv(SocketBase s, byte[][] a, int count, SendReceiveOptions flags)
        {
            if (s == null || !s.CheckTag())
            {
                throw NetMQException.Create(ErrorCode.EFAULT);
            }
            Msg msg;

            for (int i = 0; i < count; ++i)
            {
                msg = new Msg(a[i]);
                if (i == count - 1)
                {
                    flags = flags & ~SendReceiveOptions.SendMore;
                }
                SendMsg(s, msg, flags);
            }
        }
示例#9
0
文件: Req.cs 项目: ryanjshaw/netmq
        protected override bool XSend(ref Msg msg, SendReceiveOptions flags)
        {
            //  If we've sent a request and we still haven't got the reply,
            //  we can't send another request.
            if (m_receivingReply)
            {
                throw NetMQException.Create("Cannot send another request", ErrorCode.EFSM);
            }

            bool isMessageSent;

            //  First part of the request is the request identity.
            if (m_messageBegins)
            {
                Msg bottom = new Msg();
                bottom.InitEmpty();
                bottom.SetFlags(MsgFlags.More);
                isMessageSent = base.XSend(ref bottom, 0);

                if (!isMessageSent)
                {
                    return(false);
                }

                m_messageBegins = false;
            }

            bool more = msg.HasMore;

            isMessageSent = base.XSend(ref msg, flags);

            if (!isMessageSent)
            {
                return(false);
            }
            //  If the request was fully sent, flip the FSM into reply-receiving state.
            else if (!more)
            {
                m_receivingReply = true;
                m_messageBegins  = true;
            }

            return(true);
        }
示例#10
0
        public void OutCompleted(SocketError socketError, int bytesTransferred)
        {
            if (socketError != SocketError.Success)
            {
                m_ioObject.RemoveSocket(m_s);
                m_handleValid = false;

                Close();

                if (socketError == SocketError.ConnectionRefused || socketError == SocketError.TimedOut ||
                    socketError == SocketError.ConnectionAborted ||
                    socketError == SocketError.HostUnreachable || socketError == SocketError.NetworkUnreachable ||
                    socketError == SocketError.NetworkDown)
                {
                    AddReconnectTimer();
                }
                else
                {
                    throw NetMQException.Create(socketError);
                }
            }
            else
            {
                m_ioObject.RemoveSocket(m_s);
                m_handleValid = false;

                m_s.NoDelay = true;

                //Utils.TuneTcpKeepalives(m_s, m_options.TcpKeepalive, m_options.TcpKeepaliveCnt, m_options.TcpKeepaliveIdle, m_options.TcpKeepaliveIntvl);

                //  Create the engine object for this connection.
                StreamEngine engine = new StreamEngine(m_s, m_options, m_endpoint);

                m_socket.EventConnected(m_endpoint, m_s);

                m_s = null;

                //  Attach the engine to the corresponding session object.
                SendAttach(m_session, engine);

                //  Shut the connecter down.
                Terminate();
            }
        }
示例#11
0
文件: PgmSender.cs 项目: r618/netmq
        /// <summary>
        /// This method is called when a message Send operation has been completed.
        /// </summary>
        /// <param name="socketError">a SocketError value that indicates whether Success or an error occurred</param>
        /// <param name="bytesTransferred">the number of bytes that were transferred</param>
        /// <exception cref="NetMQException">A non-recoverable socket error occurred.</exception>
        public override void OutCompleted(SocketError socketError, int bytesTransferred)
        {
            if (m_state == State.Connecting)
            {
                if (socketError == SocketError.Success)
                {
                    m_state     = State.Active;
                    m_writeSize = 0;

                    BeginSending();
                }
                else
                {
                    m_state = State.Error;
                    NetMQException.Create(socketError);
                }
            }
            else if (m_state == State.Active)
            {
                // We can write either all data or 0 which means rate limit reached.
                if (socketError == SocketError.Success && bytesTransferred == m_writeSize)
                {
                    m_writeSize = 0;

                    BeginSending();
                }
                else
                {
                    if (socketError == SocketError.ConnectionReset)
                    {
                        Error();
                    }
                    else
                    {
                        throw NetMQException.Create(socketError.ToErrorCode());
                    }
                }
            }
            else
            {
                Debug.Assert(false);
            }
        }
示例#12
0
        // Receiving functions.

        public static Msg Recv(SocketBase s, SendReceiveOptions flags)
        {
            if (s == null || !s.CheckTag())
            {
                throw NetMQException.Create(ErrorCode.EFAULT);
            }
            Msg msg = RecvMsg(s, flags);

            if (msg == null)
            {
                return(null);
            }

            //  At the moment an oversized message is silently truncated.
            //  TODO: Build in a notification mechanism to report the overflows.
            //int to_copy = nbytes < len_ ? nbytes : len_;

            return(msg);
        }
示例#13
0
文件: PgmSender.cs 项目: r618/netmq
        private void BeginSending()
        {
            // If write buffer is empty,  try to read new data from the encoder.
            if (m_writeSize == 0)
            {
                // First two bytes (sizeof uint16_t) are used to store message
                // offset in following steps. Note that by passing our buffer to
                // the get data function we prevent it from returning its own buffer.
                var bf     = new ByteArraySegment(m_outBuffer, sizeof(ushort));
                int bfsz   = m_outBufferSize - sizeof(ushort);
                int offset = -1;
                m_encoder.GetData(ref bf, ref bfsz, ref offset);

                // If there are no data to write stop polling for output.
                if (bfsz == 0)
                {
                    m_state = State.ActiveSendingIdle;
                    return;
                }

                // Put offset information in the buffer.
                m_writeSize = bfsz + sizeof(ushort);

                m_outBuffer.PutUnsignedShort(m_options.Endian, offset == -1 ? (ushort)0xffff : (ushort)offset, 0);
            }

            try
            {
                m_socket.Send((byte[])m_outBuffer, m_outBuffer.Offset, m_writeSize, SocketFlags.None);
            }
            catch (SocketException ex)
            {
                if (ex.SocketErrorCode == SocketError.ConnectionReset)
                {
                    Error();
                }
                else
                {
                    throw NetMQException.Create(ex.SocketErrorCode, ex);
                }
            }
        }
示例#14
0
        public Endpoint FindEndpoint(String addr)
        {
            Endpoint endpoint = null;

            lock (m_endpointsSync)
            {
                endpoint = m_endpoints[addr];
                if (endpoint == null)
                {
                    throw NetMQException.Create(ErrorCode.ECONNREFUSED);
                }

                //  Increment the command sequence number of the peer so that it won't
                //  get deallocated until "bind" command is issued by the caller.
                //  The subsequent 'bind' has to be called with inc_seqnum parameter
                //  set to false, so that the seqnum isn't incremented twice.
                endpoint.Socket.IncSeqnum();
            }
            return(endpoint);
        }
示例#15
0
        /// <param name="socketError">the SocketError that resulted from the read - which could be Success (no error at all)</param>
        /// <param name="bytesTransferred">this indicates the number of bytes that were transferred in the read</param>
        /// <returns>the number of bytes transferred if successful, -1 otherwise</returns>
        /// <exception cref="NetMQException">If the socketError is not Success then it must be a valid recoverable error or the number of bytes transferred must be zero.</exception>
        /// <remarks>
        /// If socketError is SocketError.Success and bytesTransferred is > 0, then this returns bytesTransferred.
        /// If bytes is zero, or the socketError is one of NetworkDown, NetworkReset, HostUn, Connection Aborted, TimedOut, or ConnectionReset, - then -1 is returned.
        /// Otherwise, a NetMQException is thrown.
        /// </remarks>
        private static int EndRead(SocketError socketError, int bytesTransferred)
        {
            if (socketError == SocketError.Success && bytesTransferred > 0)
            {
                return(bytesTransferred);
            }

            if (bytesTransferred == 0 ||
                socketError == SocketError.NetworkDown ||
                socketError == SocketError.NetworkReset ||
                socketError == SocketError.HostUnreachable ||
                socketError == SocketError.ConnectionAborted ||
                socketError == SocketError.TimedOut ||
                socketError == SocketError.ConnectionReset)
            {
                return(-1);
            }

            throw NetMQException.Create(socketError);
        }
示例#16
0
 public void BeginReceive()
 {
     m_data.Reset();
     try
     {
         m_handle.Receive((byte[])m_data);
     }
     catch (SocketException ex)
     {
         // For a UDP datagram socket, this error would indicate that a previous
         // send operation resulted in an ICMP "Port Unreachable" message.
         if (ex.SocketErrorCode == SocketError.ConnectionReset)
         {
             Error();
         }
         else
         {
             throw NetMQException.Create(ex.SocketErrorCode, ex);
         }
     }
 }
示例#17
0
文件: Ctx.cs 项目: lovmoen/netmq
        public void UnregisterEndpoint(string addr, SocketBase socket)
        {
            lock (m_endpointsSync)
            {
                Endpoint endpoint;

                if (m_endpoints.TryGetValue(addr, out endpoint))
                {
                    if (socket != endpoint.Socket)
                    {
                        throw NetMQException.Create(ErrorCode.ENOENT);
                    }

                    m_endpoints.Remove(addr);
                }
                else
                {
                    throw NetMQException.Create(ErrorCode.ENOENT);
                }
            }
        }
示例#18
0
        public void Run(PairSocket shim, object[] args, CancellationToken token)
        {
            if (args == null || args.Count() != 1 || (string)args[0] != "Hello World")
            {
                throw new InvalidOperationException(
                          "Args were not correct, expected 'Hello World'");
            }

            while (!token.IsCancellationRequested)
            {
                //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 = null;

                //this may throw NetMQException if we have disposed of the actor
                //end of the pipe, and the CancellationToken.IsCancellationRequested
                //did not get picked up this loop cycle
                msg = shim.ReceiveMessage();

                if (msg == null)
                {
                    break;
                }

                if (msg[0].ConvertToString() == "ECHO")
                {
                    shim.Send(string.Format("ECHO BACK : {0}",
                                            msg[1].ConvertToString()));
                }
                else
                {
                    throw NetMQException.Create("Unexpected command",
                                                ErrorCode.EFAULT);
                }
            }
        }
示例#19
0
        /// <summary>
        /// Set address to listen on.
        /// </summary>
        /// <param name="addr">a string denoting the address to set this to</param>
        public virtual void SetAddress([NotNull] string addr)
        {
            m_address.Resolve(addr, m_options.IPv4Only);

            try
            {
                m_handle = AsyncSocket.Create(m_address.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                Debug.Assert(m_handle != null);

                if (!m_options.IPv4Only && m_address.Address.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    try
                    {
                        // This is not supported on old windows operation system and might throw exception
                        m_handle.SetSocketOption(SocketOptionLevel.IPv6, IPv6Only, 0);
                    }
                    catch
                    {
                    }
                }

                m_handle.ExclusiveAddressUse = false;
                m_handle.Bind(m_address.Address);
                m_handle.Listen(m_options.Backlog);

                // Copy the port number after binding in case we requested a system-allocated port number (TCP port zero)
                m_address.Address.Port = m_handle.LocalEndPoint.Port;
                m_endpoint             = m_address.ToString();

                m_socket.EventListening(m_endpoint, m_handle);

                m_port = m_handle.LocalEndPoint.Port;
            }
            catch (SocketException ex)
            {
                Close();
                throw NetMQException.Create(ex);
            }
        }
示例#20
0
        //  Check whether transport protocol, as specified in connect or
        //  bind, is available and compatible with the socket type.
        private void CheckProtocol(String protocol)
        {
            //  First check out whether the protcol is something we are aware of.
            if (!protocol.Equals("inproc") &&
                !protocol.Equals("ipc") && !protocol.Equals("tcp") &&
                !protocol.Equals("pgm") && !protocol.Equals("epgm"))
            {
                throw NetMQException.Create(ErrorCode.EPROTONOSUPPORT);
            }

            //  Check whether socket type and transport protocol match.
            //  Specifically, multicast protocols can't be combined with
            //  bi-directional messaging patterns (socket types).
            if ((protocol.Equals("pgm") || protocol.Equals("epgm")) &&
                m_options.SocketType != ZmqSocketType.Pub && m_options.SocketType != ZmqSocketType.Sub &&
                m_options.SocketType != ZmqSocketType.Xpub && m_options.SocketType != ZmqSocketType.Xsub)
            {
                throw NetMQException.Create(protocol + ",type=" + m_options.SocketType, ErrorCode.EPROTONOSUPPORT);
            }

            //  Protocol is available.
        }
示例#21
0
        //  Set address to listen on. return the used port
        public virtual void SetAddress(String addr)
        {
            m_address.Resolve(addr, m_options.IPv4Only);

            m_endpoint = m_address.ToString();
            try
            {
                m_handle =
                    new Socket(m_address.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                if (!m_options.IPv4Only && m_address.Address.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    try
                    {
                        // This is not supported on old windows operation system and might throw exception
                        m_handle.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 0);
                    }
                    catch
                    {
                    }
                }

                //handle.Blocking = false;

                m_handle.ExclusiveAddressUse = false;
                m_handle.Bind(m_address.Address);
                m_handle.Listen(m_options.Backlog);
            }
            catch (SocketException ex)
            {
                Close();
                throw NetMQException.Create(ex);
            }

            m_socket.EventListening(m_endpoint, m_handle);

            m_port = ((IPEndPoint)m_handle.LocalEndPoint).Port;
        }
示例#22
0
文件: Req.cs 项目: ryanjshaw/netmq
            override public void PushMsg(ref Msg msg)
            {
                switch (m_state)
                {
                case State.Bottom:
                    if (msg.Flags == MsgFlags.More && msg.Size == 0)
                    {
                        m_state = State.Body;
                        base.PushMsg(ref msg);
                    }
                    break;

                case State.Body:
                    if (msg.Flags == MsgFlags.More)
                    {
                        base.PushMsg(ref msg);
                    }
                    else if (msg.Flags == 0)
                    {
                        m_state = State.Bottom;
                        base.PushMsg(ref msg);
                    }
                    break;

                case State.Identity:
                    if (msg.Flags == 0)
                    {
                        m_state = State.Bottom;
                        base.PushMsg(ref msg);
                    }
                    break;

                default:

                    throw NetMQException.Create(ErrorCode.EFAULT);
                }
            }
示例#23
0
        /// <exception cref="InvalidException">Unable to parse the address's port number, or the IP address could not be parsed.</exception>
        /// <exception cref="NetMQException">Error establishing underlying socket.</exception>
        public void Init([NotNull] string network)
        {
            this.m_address = new PgmAddress(network);

            this.m_pgmSocket = new PgmSocket(this.m_options, PgmSocketType.Listener, this.m_address);
            this.m_pgmSocket.Init();

            this.m_handle = this.m_pgmSocket.Handle;

            try
            {
                this.m_handle.Bind(this.m_address.Address);
                this.m_pgmSocket.InitOptions();
                this.m_handle.Listen(this.m_options.Backlog);
            }
            catch (SocketException ex)
            {
                this.Close();

                throw NetMQException.Create(ex);
            }

            this.m_socket.EventListening(this.m_address.ToString(), this.m_handle);
        }
示例#24
0
        public void Close()
        {
            if (!Check())
            {
                throw NetMQException.Create(ErrorCode.EFAULT);
            }

            if (m_type == MsgType.Pool)
            {
                // if not shared or reference counter drop to zero
                if ((m_flags & MsgFlags.Shared) == 0 || m_atomicCounter.Decrement() == 0)
                {
                    BufferPool.Return(m_data);
                }

                m_atomicCounter.Dispose();
                m_atomicCounter = null;
            }

            m_data = null;

            //  Make the message invalid.
            m_type = MsgType.Invalid;
        }
示例#25
0
文件: PgmSession.cs 项目: zredb/netmq
 public void BeginReceive()
 {
     m_data.Reset();
     try
     {
         m_handle.Receive((byte[])m_data);
     }
     catch (SocketException ex)
     {
         // For a UDP datagram socket, this error would indicate that a previous
         // send operation resulted in an ICMP "Port Unreachable" message.
         if (ex.SocketErrorCode == SocketError.ConnectionReset)
         {
             Error();
         }
         // ** Berkeley Description: A connection abort was caused internal to your host machine.
         // The software caused a connection abort because there is no space on the socket's queue
         // and the socket cannot receive further connections.
         // ** WinSock description: The error can occur when the local network system aborts a connection.
         // This would occur if WinSock aborts an established connection after data retransmission
         // fails (receiver never acknowledges data sent on a datastream socket).
         // ** Windows Sockets Error Codes: Software caused connection abort.
         // An established connection was aborted by the software in your host computer,
         // possibly due to a data transmission time -out or protocol error.
         // ** WSARecv Error Code Description: The virtual circuit was terminated due to a
         // time -out or other failure.
         else if (ex.SocketErrorCode == SocketError.ConnectionAborted)
         {
             Error();
         }
         else
         {
             throw NetMQException.Create(ex.SocketErrorCode, ex);
         }
     }
 }
示例#26
0
        //  Set address to listen on.
        public virtual void SetAddress(String addr)
        {
            m_address.Resolve(addr, m_options.IPv4Only);

            m_endpoint = m_address.ToString();
            try
            {
                m_handle =
                    new Socket(m_address.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                //handle.Blocking = false;

                m_handle.ExclusiveAddressUse = false;
                m_handle.Bind(m_address.Address);
                m_handle.Listen(m_options.Backlog);
            }
            catch (SocketException ex)
            {
                Close();
                throw NetMQException.Create(ex);
            }

            m_socket.EventListening(m_endpoint, m_handle);
        }
示例#27
0
        /// <exception cref="InvalidException">Unable to parse the address's port number, or the IP address could not be parsed.</exception>
        /// <exception cref="NetMQException">Error establishing underlying socket.</exception>
        public void Init(string network)
        {
            m_address = new PgmAddress(network);

            m_pgmSocket = new PgmSocket(m_options, PgmSocketType.Listener, m_address);
            m_pgmSocket.Init();

            m_handle = m_pgmSocket.Handle;

            try
            {
                m_handle.Bind(m_address.Address);
                m_pgmSocket.InitOptions();
                m_handle.Listen(m_options.Backlog);
            }
            catch (SocketException ex)
            {
                Close();

                throw NetMQException.Create(ex);
            }

            m_socket.EventListening(m_address.ToString(), m_handle);
        }
示例#28
0
        public static int Poll(PollItem[] items, int itemsCount, int timeout)
        {
            if (items == null)
            {
                throw NetMQException.Create(ErrorCode.EFAULT);
            }
            if (itemsCount == 0)
            {
                if (timeout <= 0)
                {
                    return(0);
                }
                Thread.Sleep(timeout);
                return(0);
            }

            bool firstPass = true;
            int  nevents   = 0;

            List <Socket> writeList = new List <Socket>();
            List <Socket> readList  = new List <Socket>();
            List <Socket> errorList = new List <Socket>();

            for (int i = 0; i < itemsCount; i++)
            {
                var pollItem = items[i];

                if (pollItem.Socket != null)
                {
                    if (pollItem.Events != PollEvents.None)
                    {
                        readList.Add(pollItem.Socket.FD);
                    }
                }
                else
                {
                    if ((pollItem.Events & PollEvents.PollIn) == PollEvents.PollIn)
                    {
                        readList.Add(pollItem.FileDescriptor);
                    }

                    if ((pollItem.Events & PollEvents.PollOut) == PollEvents.PollOut)
                    {
                        writeList.Add(pollItem.FileDescriptor);
                    }

                    if ((pollItem.Events & PollEvents.PollError) == PollEvents.PollError)
                    {
                        errorList.Add(pollItem.FileDescriptor);
                    }
                }
            }

            List <Socket> inset    = new List <Socket>(readList.Count);
            List <Socket> outset   = new List <Socket>(writeList.Count);
            List <Socket> errorset = new List <Socket>(errorList.Count);

            Stopwatch stopwatch = null;

            while (true)
            {
                int currentTimeoutMicroSeconds;

                if (firstPass)
                {
                    currentTimeoutMicroSeconds = 0;
                }
                else if (timeout == -1)
                {
                    currentTimeoutMicroSeconds = -1;
                }
                else
                {
                    currentTimeoutMicroSeconds = (int)((timeout - stopwatch.ElapsedMilliseconds) * 1000);

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

                inset.AddRange(readList.Where(x => x.Connected || x.ProtocolType != ProtocolType.Tcp));
                outset.AddRange(writeList.Where(x => x.Connected || x.ProtocolType != ProtocolType.Tcp));
                errorset.AddRange(errorList.Where(x => x.Connected || x.ProtocolType != ProtocolType.Tcp));

                try
                {
                    System.Net.Sockets.Socket.Select(inset, outset, errorset, currentTimeoutMicroSeconds);
                }
                catch (SocketException ex)
                {
                    throw NetMQException.Create(ErrorCode.ESOCKET, ex);
                }

                for (int i = 0; i < itemsCount; i++)
                {
                    var pollItem = items[i];

                    pollItem.ResultEvent = PollEvents.None;

                    if (pollItem.Socket != null)
                    {
                        PollEvents events = (PollEvents)GetSocketOption(pollItem.Socket, ZmqSocketOptions.Events);

                        if ((pollItem.Events & PollEvents.PollIn) == PollEvents.PollIn &&
                            (events & PollEvents.PollIn) == PollEvents.PollIn)
                        {
                            pollItem.ResultEvent |= PollEvents.PollIn;
                        }

                        if ((pollItem.Events & PollEvents.PollOut) == PollEvents.PollOut &&
                            (events & PollEvents.PollOut) == PollEvents.PollOut)
                        {
                            pollItem.ResultEvent |= PollEvents.PollOut;
                        }
                    }
                    else
                    {
                        if (inset.Contains(pollItem.FileDescriptor))
                        {
                            pollItem.ResultEvent |= PollEvents.PollIn;
                        }

                        if (outset.Contains(pollItem.FileDescriptor))
                        {
                            pollItem.ResultEvent |= PollEvents.PollOut;
                        }

                        if (errorset.Contains(pollItem.FileDescriptor))
                        {
                            pollItem.ResultEvent |= PollEvents.PollError;
                        }
                    }

                    if (pollItem.ResultEvent != PollEvents.None)
                    {
                        nevents++;
                    }
                }

                inset.Clear();
                outset.Clear();
                errorset.Clear();

                if (timeout == 0)
                {
                    break;
                }

                if (nevents > 0)
                {
                    break;
                }

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

                    continue;
                }

                if (firstPass)
                {
                    stopwatch = Stopwatch.StartNew();
                    firstPass = false;
                    continue;
                }

                if (stopwatch.ElapsedMilliseconds > timeout)
                {
                    break;
                }
            }

            return(nevents);
        }
示例#29
0
文件: Sub.cs 项目: wbj808178/netmq
 protected override bool XSend(Msg msg, SendReceiveOptions flags)
 {
     //  Overload the XSUB's send.
     throw NetMQException.Create("Send not supported on sub socket", ErrorCode.ENOTSUP);
 }
示例#30
0
文件: Stream.cs 项目: wbj808178/netmq
        protected override bool XSend(Msg msg, SendReceiveOptions flags)
        {
            //  If this is the first part of the message it's the ID of the
            //  peer to send the message to.
            if (!m_moreOut)
            {
                Debug.Assert(m_currentOut == null);

                //  If we have malformed message (prefix with no subsequent message)
                //  then just silently ignore it.
                //  TODO: The connections should be killed instead.
                if (msg.HasMore)
                {
                    //  Find the pipe associated with the identity stored in the prefix.
                    //  If there's no such pipe just silently ignore the message, unless
                    //  mandatory is set.
                    Blob    identity = new Blob(msg.Data);
                    Outpipe op;

                    if (m_outpipes.TryGetValue(identity, out op))
                    {
                        m_currentOut = op.Pipe;
                        if (!m_currentOut.CheckWrite())
                        {
                            op.Active    = false;
                            m_currentOut = null;
                            return(false);
                        }
                    }
                    else
                    {
                        throw NetMQException.Create(ErrorCode.EHOSTUNREACH);
                    }
                }

                m_moreOut = true;

                return(true);
            }

            //  Ignore the MORE flag
            msg.ResetFlags(MsgFlags.More);

            //  This is the last part of the message.
            m_moreOut = false;

            //  Push the message into the pipe. If there's no out pipe, just drop it.
            if (m_currentOut != null)
            {
                if (msg.Size == 0)
                {
                    m_currentOut.Terminate(false);
                    m_currentOut = null;
                    return(true);
                }

                bool ok = m_currentOut.Write(msg);
                if (ok)
                {
                    m_currentOut.Flush();
                }

                m_currentOut = null;
            }
            else
            {
            }

            //  Detach the message from the data buffer.

            return(true);
        }