Exemple #1
0
        public void AddSocket(AsyncSocket socket, IProactorEvents proactorEvents)
        {
            var item = new Item(proactorEvents);
            m_sockets.Add(socket, item);

            m_completionPort.AssociateSocket(socket, item);
            AdjustLoad(1);
        }
Exemple #2
0
        public void RemoveSocket(AsyncSocket socket)
        {
            AdjustLoad(-1);

            var item = m_sockets[socket];
            m_sockets.Remove(socket);
            item.Cancelled = true;
        }
Exemple #3
0
 /// <summary>
 /// Create a new TcpListener on the given IOThread and socket.
 /// </summary>
 /// <param name="ioThread">the IOThread for this to live within</param>
 /// <param name="socket">a SocketBase to listen on</param>
 /// <param name="options">socket-related Options</param>
 public TcpListener([NotNull] IOThread ioThread, [NotNull] SocketBase socket, [NotNull] Options options)
     : base(ioThread, options)
 {
     m_ioObject = new IOObject(ioThread);
     m_address = new TcpAddress();
     m_handle = null;
     m_socket = socket;
 }
 internal CompletionStatus(AsyncSocket asyncSocket, object state, OperationType operationType, SocketError socketError, int bytesTransferred) :
     this()
 {
     AsyncSocket      = asyncSocket;
     State            = state;
     OperationType    = operationType;
     SocketError      = socketError;
     BytesTransferred = bytesTransferred;
 }
Exemple #5
0
 internal CompletionStatus(AsyncSocket asyncSocket, object state, OperationType operationType, SocketError socketError, int bytesTransferred) : 
     this()
 {
     AsyncSocket = asyncSocket;
     State = state;
     OperationType = operationType;
     SocketError = socketError;
     BytesTransferred = bytesTransferred;
 }
Exemple #6
0
        public PgmSession( PgmSocket pgmSocket,  Options options)
        {
            m_handle = pgmSocket.Handle;
            m_options = options;
            m_data = new byte[Config.PgmMaxTPDU];
            m_joined = false;

            m_state = State.Idle;
        }
Exemple #7
0
        public void SetAddress(Uri uri)
        {
            IPAddress ipAddress;

            if (uri.Host == "*")
                ipAddress = IPAddress.IPv6Any;
            else if (!IPAddress.TryParse(uri.Host, out ipAddress))
            {
                var availableAddresses = Dns.GetHostEntry(uri.Host).AddressList;

                // higher priority to IPv6
                ipAddress = availableAddresses.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetworkV6);

                if (ipAddress == null)
                    ipAddress = availableAddresses.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);

                if (ipAddress == null)
                    throw new NetMQException(ErrorCode.Invalid, string.Format("unable to find an IP address for {0}", uri.Host));
            }

            m_endPoint = new IPEndPoint(ipAddress, uri.Port);

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

                if (ipAddress.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.Bind(m_endPoint);
                m_handle.Listen(Options.Backlog);
            }
            catch (SocketException ex)
            {
                if (m_handle != null)
                {
                    m_handle.Dispose();
                    m_handle = null;
                }

                throw NetMQException.FromSocketError(ex.SocketErrorCode);
            }
        }
Exemple #8
0
        public void Init( PgmAddress pgmAddress)
        {
            m_pgmAddress = pgmAddress;

            m_pgmSocket = new PgmSocket(m_options, PgmSocketType.Publisher, (PgmAddress)m_addr.Resolved);
            m_pgmSocket.Init();

            m_socket = m_pgmSocket.Handle;

            var localEndpoint = new IPEndPoint(IPAddress.Any, 0);

            m_socket.Bind(localEndpoint);

            m_pgmSocket.InitOptions();

            m_outBufferSize = Config.PgmMaxTPDU;
            m_outBuffer = new ByteArraySegment(new byte[m_outBufferSize]);
        }
Exemple #9
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);
        }
Exemple #10
0
        /// <summary>
        /// Perform initialization of this PgmSocket, including creating the socket handle.
        /// </summary>
        internal void Init()
        {
            #if DEBUG
            // Don't want to bloat the code with excessive debugging information, unless this is a DEBUG build.  jh
            try
            {
            #endif
                Handle = AsyncSocket.Create(AddressFamily.InterNetwork, SocketType.Rdm, PgmProtocolType);
            #if DEBUG
            }
            catch (SocketException x)
            {
                string xMsg = $"SocketException with SocketErrorCode={x.SocketErrorCode}, Message={x.Message}, in PgmSocket.Init, within AsyncSocket.Create(AddressFamily.InterNetwork, SocketType.Rdm, PGM_PROTOCOL_TYPE), {this}";
                Debug.WriteLine(xMsg);
                // If running on Microsoft Windows, suggest to the developer that he may need to install MSMQ in order to get PGM socket support.

            #if NETSTANDARD1_3
                bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
            #else
                PlatformID p = Environment.OSVersion.Platform;
                bool isWindows = true;
                switch (p)
                {
                    case PlatformID.Win32NT:
                        break;
                    case PlatformID.Win32S:
                        break;
                    case PlatformID.Win32Windows:
                        break;
                    default:
                        isWindows = false;
                        break;
                }
            #endif
                if (isWindows)
                {
                    Debug.WriteLine("For Microsoft Windows, you may want to check to see whether you have installed MSMQ on this host, to get PGM socket support.");
                }
                throw new FaultException(innerException: x, message: xMsg);
            }
            #endif
            Handle.ExclusiveAddressUse = false;
            Handle.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        }
Exemple #11
0
 public abstract void AssociateSocket(AsyncSocket socket, object state = null);
Exemple #12
0
 public void Destroy()
 {
     if (m_handle != null)
     {
         try
         {
             m_handle.Dispose();
         }
         catch (SocketException)
         {}
         m_handle = null;
     }
 }
Exemple #13
0
        /// <summary>
        /// Create a new TcpConnector object.
        /// </summary>
        /// <param name="ioThread">the I/O-thread for this TcpConnector to live on.</param>
        /// <param name="session">the session that will contain this</param>
        /// <param name="options">Options that define this new TcpC</param>
        /// <param name="addr">the Address for this Tcp to connect to</param>
        /// <param name="delayedStart">this boolean flag dictates whether to wait before trying to connect</param>
        public TcpConnector([NotNull] IOThread ioThread, [NotNull] SessionBase session, [NotNull] Options options, [NotNull] Address addr, bool delayedStart)
            : base(ioThread, options)
        {
            m_ioObject = new IOObject(ioThread);
            m_addr = addr;
            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;
        }
Exemple #14
0
        /// <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>
        /// <exception cref="NetMQException">If the socketError is not Success then it must be a valid recoverable error.</exception>
        public void OutCompleted(SocketError socketError, int bytesTransferred)
        {
            if (socketError != SocketError.Success)
            {
                m_ioObject.RemoveSocket(m_s);
                m_handleValid = false;

                Close();

                // Try again to connect after a time,
                // as long as the error is one of these..
                if (socketError == SocketError.ConnectionRefused || socketError == SocketError.TimedOut ||
                    socketError == SocketError.ConnectionAborted ||
                    socketError == SocketError.HostUnreachable || socketError == SocketError.NetworkUnreachable ||
                    socketError == SocketError.NetworkDown || socketError == SocketError.AccessDenied)
                {
                    AddReconnectTimer();
                }
                else
                {
                    throw NetMQException.Create(socketError);
                }
            }
            else
            {
                m_ioObject.RemoveSocket(m_s);
                m_handleValid = false;

                m_s.NoDelay = true;

                // As long as the TCP keep-alive option is not -1 (indicating no change),
                if (m_options.TcpKeepalive != -1)
                {
                    // Set the TCP keep-alive option values to the underlying socket.
                    m_s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, m_options.TcpKeepalive);

                    if (m_options.TcpKeepaliveIdle != -1 && m_options.TcpKeepaliveIntvl != -1)
                    {
                        // Write the TCP keep-alive options to a byte-array, to feed to the IOControl method..
                        var bytes = new ByteArraySegment(new byte[12]);

                        Endianness endian = BitConverter.IsLittleEndian ? Endianness.Little : Endianness.Big;

                        bytes.PutInteger(endian, m_options.TcpKeepalive, 0);
                        bytes.PutInteger(endian, m_options.TcpKeepaliveIdle, 4);
                        bytes.PutInteger(endian, m_options.TcpKeepaliveIntvl, 8);

                        m_s.IOControl(IOControlCode.KeepAliveValues, (byte[])bytes, null);
                    }
                }

                // Create the engine object for this connection.
                var 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 connector down.
                Terminate();
            }
        }
 public abstract void AssociateSocket(AsyncSocket socket, object state = null);
Exemple #16
0
        /// <summary>
        /// Close the listening socket.
        /// </summary>
        private void Close()
        {
            if (m_handle == null)
                return;

            try
            {
                m_handle.Dispose();
                m_socket.EventClosed(m_endpoint, m_handle);
            }
            catch (SocketException ex)
            {
                m_socket.EventCloseFailed(m_endpoint, ex.SocketErrorCode.ToErrorCode());
            }

            if (m_acceptedSocket != null)
            {
                try
                {
                    m_acceptedSocket.Dispose();
                }
                catch (SocketException)
                {
                }
            }

            m_acceptedSocket = null;
            m_handle = null;
        }
Exemple #17
0
        private void Accept()
        {
            m_acceptedSocket = AsyncSocket.Create(m_address.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            // start accepting socket async
            m_handle.Accept(m_acceptedSocket);

            // Disable TIME_WAIT tcp state
            if (m_options.DisableTimeWait)
                m_handle.LingerState = new LingerOption(true, 0);
        }
Exemple #18
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);
            }
        }
Exemple #19
0
 public abstract void Accept(AsyncSocket socket);
Exemple #20
0
 /// <summary>
 /// Remove the given socket from the Proactor.
 /// </summary>
 /// <param name="socket">the AsyncSocket to remove</param>
 public void RemoveSocket( AsyncSocket socket)
 {
     m_ioThread.Proactor.RemoveSocket(socket);
 }
Exemple #21
0
 /// <summary>
 /// Add the given socket to the Proactor.
 /// </summary>
 /// <param name="socket">the AsyncSocket to add</param>
 public void AddSocket( AsyncSocket socket)
 {
     m_ioThread.Proactor.AddSocket(socket, this);
 }
Exemple #22
0
 /// <summary>
 /// Create a new NetMQMonitorSocketEventArgs that contains the given monitor, address, and socket.
 /// </summary>
 /// <param name="monitor">The <see cref="NetMQMonitor"/> that raised this event.</param>
 /// <param name="address">The address of the event.</param>
 /// <param name="socketEvent">The type of socket event that occurred.</param>
 /// <param name="socket">The socket upon which this event occurred.</param>
 public NetMQMonitorSocketEventArgs( NetMQMonitor monitor,  string address,  AsyncSocket socket, SocketEvents socketEvent)
     : base(monitor, address, socketEvent)
 {
     Socket = socket;
 }
Exemple #23
0
 internal void InitReceiver()
 {
     Handle = AsyncSocket.Create(AddressFamily.InterNetwork, SocketType.Rdm, PgmProtocolType);
 }
Exemple #24
0
        private void Close()
        {
            if (m_handle == null)
                return;

            try
            {
                m_handle.Dispose();
                m_socket.EventClosed(m_address.ToString(), m_handle);
            }
            catch (SocketException ex)
            {
                m_socket.EventCloseFailed(m_address.ToString(), ex.SocketErrorCode.ToErrorCode());
            }
            catch (NetMQException ex)
            {
                m_socket.EventCloseFailed(m_address.ToString(), ex.ErrorCode);
            }

            m_handle = null;
        }
Exemple #25
0
 public static void Bind(this AsyncSocket socket, IPAddress ipAddress, int port)
 {
     socket.Bind(new IPEndPoint(ipAddress, port));
 }
Exemple #26
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="socketError"></param>
        /// <param name="bytesTransferred"></param>
        /// <exception cref="NetMQException">a non-recoverable socket error occurred.</exception>
        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;

                if (m_options.TcpKeepalive != -1)
                {
                    m_s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, m_options.TcpKeepalive);

                    if (m_options.TcpKeepaliveIdle != -1 && m_options.TcpKeepaliveIntvl != -1)
                    {
                        var bytes = new ByteArraySegment(new byte[12]);

                        Endianness endian = BitConverter.IsLittleEndian ? Endianness.Little : Endianness.Big;

                        bytes.PutInteger(endian, m_options.TcpKeepalive, 0);
                        bytes.PutInteger(endian, m_options.TcpKeepaliveIdle, 4);
                        bytes.PutInteger(endian, m_options.TcpKeepaliveIntvl, 8);

                        m_s.IOControl(IOControlCode.KeepAliveValues, (byte[])bytes, null);
                    }
                }

                //  Create the engine object for this connection.
                var 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 connector down.
                Terminate();
            }
        }
Exemple #27
0
 public static void Send(this AsyncSocket socket, byte[] buffer)
 {
     socket.Send(buffer, 0, buffer.Length, SocketFlags.None);
 }
Exemple #28
0
        /// <summary>
        /// Internal function to start the actual connection establishment.
        /// </summary>
        private void StartConnecting()
        {
            Debug.Assert(m_s == null);

            // Create the socket.
            try
            {
                m_s = AsyncSocket.Create(m_addr.Resolved.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            }
            catch (SocketException)
            {
                AddReconnectTimer();
                return;
            }

            m_ioObject.AddSocket(m_s);
            m_handleValid = true;

            // Connect to the remote peer.
            try
            {
                m_s.Connect(m_addr.Resolved.Address.Address, m_addr.Resolved.Address.Port);
                m_socket.EventConnectDelayed(m_endpoint, ErrorCode.InProgress);
            }
            catch (SocketException ex)
            {
                OutCompleted(ex.SocketErrorCode, 0);
            }
        }
Exemple #29
0
        public void Init([NotNull] PgmAddress pgmAddress)
        {
            m_pgmAddress = pgmAddress;

            m_pgmSocket = new PgmSocket(m_options, PgmSocketType.Publisher, (PgmAddress)m_addr.Resolved);
            m_pgmSocket.Init();

            m_socket = m_pgmSocket.Handle;

            var localEndpoint = new IPEndPoint(IPAddress.Any, 0);

            m_socket.Bind(localEndpoint);

            m_pgmSocket.InitOptions();

            m_outBufferSize = m_options.PgmMaxTransportServiceDataUnitLength;
            m_outBuffer = new ByteArraySegment(new byte[m_outBufferSize]);
        }
Exemple #30
0
 /// <summary>
 /// Close the connecting socket.
 /// </summary>
 private void Close()
 {
     Debug.Assert(m_s != null);
     try
     {
         m_s.Dispose();
         m_socket.EventClosed(m_endpoint, m_s);
         m_s = null;
     }
     catch (SocketException ex)
     {
         m_socket.EventCloseFailed(m_endpoint, ex.SocketErrorCode.ToErrorCode());
     }
 }
Exemple #31
0
        public StreamEngine(AsyncSocket handle, Options options, string endpoint)
        {
            m_handle = handle;
            m_insize = 0;
            m_ioEnabled = false;
            m_sendingState = SendState.Idle;
            m_receivingState = ReceiveState.Idle;
            m_outsize = 0;
            m_session = null;
            m_options = options;
            m_plugged = false;
            m_endpoint = endpoint;
            m_socket = null;
            m_encoder = null;
            m_decoder = null;
            m_actionsQueue = new Queue<StateMachineAction>();

            //  Set the socket buffer limits for the underlying socket.
            if (m_options.SendBuffer != 0)
            {
                m_handle.SendBufferSize = m_options.SendBuffer;
            }
            if (m_options.ReceiveBuffer != 0)
            {
                m_handle.ReceiveBufferSize = m_options.ReceiveBuffer;
            }
        }
Exemple #32
0
 //[Obsolete("Use Accept without parameter and GetAcceptedSocket")]
 public abstract void Accept(AsyncSocket socket);
Exemple #33
0
        private void Accept()
        {
            m_acceptedSocket = AsyncSocket.Create(m_address.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            // start accepting socket async
            m_handle.Accept(m_acceptedSocket);
        }
Exemple #34
0
 public static void Connect(this AsyncSocket socket, IPAddress ipAddress, int port)
 {
     socket.Connect(new IPEndPoint(ipAddress, port));
 }
Exemple #35
0
 public MonitorEvent(SocketEvents monitorEvent,  string addr,  AsyncSocket arg)
     : this(monitorEvent, addr, (object)arg)
 {
 }
Exemple #36
0
 public static void Receive(this AsyncSocket socket, byte[] buffer)
 {
     socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
 }
Exemple #37
0
        public void Destroy()
        {
            Debug.Assert(!m_plugged);

            if (m_handle != null)
            {
                try
                {
                    m_handle.Dispose();
                }
                catch (SocketException)
                {}
                m_handle = null;
            }
        }