Пример #1
0
        static void listener_Accept(IAsyncResult ar)
        {
            object[]     state    = (object[])ar.AsyncState;
            Socket       listener = (Socket)state[0];
            TcpExChannel channel  = (TcpExChannel)state[1];
            Socket       client   = null;

            try
            {
                try
                {
                    client = listener.EndAccept(ar);
                }
                catch (SocketException x)
                {
                    // connection forcibly closed by the client's host
                    Trace.WriteLine("TcpEx.Manager: invalid incoming connection. Got exception: {0}" + x.ToString());
                }

                // Wait for next Client request
                listener.BeginAccept(new AsyncCallback(listener_Accept), new object[] { listener, channel });
            }
            catch (ObjectDisposedException ex)
            {
                // the listener was closed
                Trace.WriteLine("TcpEx.Manager: the listener was closed. Got exception: " + ex.ToString());
                return;
            }

            // ignore invalid incoming connections
            if (client == null)
            {
                return;
            }

            try
            {
                StartListening(Connection.CreateConnection(client, channel, channel.TcpKeepAliveEnabled, channel.TcpKeepAliveTime, channel.TcpKeepAliveInterval, channel.MaxRetries, channel.RetryDelay));
            }
            catch (DuplicateConnectionException)
            {
            }
            catch (IOException ex)
            {
                // Client socket is not responding
                Trace.WriteLine("TcpEx.Manager: client socket is not responding. Got exception: " + ex.ToString());
            }
            catch (SerializationException ex)
            {
                // Client sends bad data
                Trace.WriteLine("TcpEx.Manager: client is sending bad data. Got exception: " + ex.ToString());
            }
            catch (Exception ex)
            {
                // Cannot cleanly connect to the remote party
                // it's probably not TcpEx channel that's trying to connect us
                Trace.WriteLine("TcpEx.Manager: cannot accept the incoming connection. Got exception: " + ex.ToString());
                return;
            }
        }
Пример #2
0
        static void listener_Accept(IAsyncResult ar)
        {
            object[]     state    = (object[])ar.AsyncState;
            Socket       listener = (Socket)state[0];
            TcpExChannel channel  = (TcpExChannel)state[1];
            Socket       client   = listener.EndAccept(ar);

            try
            {
                StartListening(Connection.CreateConnection(client, channel, channel.TcpKeepAliveEnabled, channel.TcpKeepAliveTime, channel.TcpKeepAliveInterval, channel.MaxRetries, channel.RetryDelay));
            }
            catch (DuplicateConnectionException)
            {
            }
            catch (IOException)
            {
                // Client socket is not responding
                //TODO: Add Tracing here!
            }
            catch (SerializationException)
            {
                // Client sends bad data
                //TODO: Add Tracing here!
            }
            // Wait for next Client request
            listener.BeginAccept(new AsyncCallback(listener_Accept), new object[] { listener, channel });
        }
Пример #3
0
        /// <summary>
        /// Stops listening of a specified channel.
        /// </summary>
        /// <param name="channel">TcpEx Channel</param>
        /// <param name="listenerAddresses">Addresses the channel is listening</param>
        public static void StopListening(TcpExChannel channel, string[] listenerAddresses)
        {
            if (channel == null)
            {
                throw new ArgumentNullException("channel");
            }

            // close running connections
            var runningConnections = Connection.GetRunningConnectionsOfChannel(channel);

            if (runningConnections != null)
            {
                while (runningConnections.Count() > 0)
                {
                    runningConnections.First().Close();
                }
            }

            // remove pending listeners if specified
            if (listenerAddresses != null)
            {
                lock (_listenersLockObject)
                {
                    foreach (var address in listenerAddresses)
                    {
                        _listeners.Remove(address);
                    }
                }
            }
        }
Пример #4
0
        /// <summary>
        /// Gets a specified connection.
        /// </summary>
        /// <param name="address">Address of the connection</param>
        /// <param name="channel">Channel of the connection</param>
        /// <param name="keepAlive">Enables or disables TCP KeepAlive for the new connection</param>
        /// <param name="keepAliveTime">Time for TCP KeepAlive in Milliseconds</param>
        /// <param name="KeepAliveInterval">Interval for TCP KeepAlive in Milliseconds</param>
        /// <param name="maxRetries">Maximum number of connection retry attempts</param>
        /// <param name="retryDelay">Delay after connection retry in milliseconds</param>
        /// <returns>Connection</returns>
        public static Connection GetConnection(string address, TcpExChannel channel, bool keepAlive, ulong keepAliveTime, ulong KeepAliveInterval, short maxRetries, int retryDelay)
        {
            if (string.IsNullOrEmpty(address))
            {
                throw new ArgumentException(LanguageResource.ArgumentException_AddressMustNotBeEmpty, "address");
            }

            if (channel == null)
            {
                throw new ArgumentNullException("channel");
            }

            Trace.WriteLine("TcpEx.Connection.GetConnection: {0}", address);

            lock (_connectionsLockObject)
            {
                if (_connections.ContainsKey(address))
                {
                    var foundConnection = _connections[address];
                    Trace.WriteLine("TcpEx.Connection found. ChannelID: {0}", foundConnection._channel.ChannelID);

                    if (foundConnection.IsClosed)
                    {
                        _connections.Remove(address);
                    }
                    else
                    {
                        return(foundConnection);
                    }
                }

                Connection connection = null;

                try
                {
                    Trace.WriteLine("TcpEx.Connection is created...");

                    connection = new Connection(address, channel, keepAlive, keepAliveTime, KeepAliveInterval, maxRetries, retryDelay);
                    if (!_connections.ContainsKey(address))
                    {
                        _connections.Add(address, connection);                         // This most often happens when using the loopback address
                    }
                    Manager.StartListening(connection);
                }
                catch (DuplicateConnectionException ex)
                {
                    connection = _connections[ex.ChannelID.ToString()];
                    _connections.Add(address, connection);
                }
                catch (FormatException formatEx)
                {
                    throw new RemotingException(string.Format(LanguageResource.RemotingException_ConnectionError, formatEx.Message), formatEx);
                }

                return(connection);
            }
        }
Пример #5
0
        /// <summary>
        /// Creates a new instance of the TcpExChannelData class.
        /// </summary>
        /// <param name="channel">Remoting channel</param>
        public TcpExChannelData(TcpExChannel channel)
        {
            Port      = channel.Port;
            ChannelID = channel.ChannelID;

            if (Port != 0)
            {
                Addresses = new List <string>(Manager.GetAddresses(Port, channel.ChannelID, false));
            }
        }
Пример #6
0
        /// <summary>
        /// Creates a new instance of the TcpExChannelData class.
        /// </summary>
        /// <param name="channel">Remoting channel</param>
        public TcpExChannelData(TcpExChannel channel)
        {
            Port = channel.Port;
            ChannelID = channel.ChannelID;

            if (Port != 0)
            {
                Addresses = new List<string>(Manager.GetAddresses(Port, channel.ChannelID, false));
            }
        }
Пример #7
0
        /// <summary>
        /// Creates a new instance of the Connection class.
        /// </summary>
        /// <param name="address">Address (IP oder DNS based)</param>
        /// <param name="channel">Remoting channel</param>
        /// <param name="keepAlive">Enables or disables TCP KeepAlive for the new connection</param>
        /// <param name="keepAliveTime">Time for TCP KeepAlive in Milliseconds</param>
        /// <param name="KeepAliveInterval">Interval for TCP KeepAlive in Milliseconds</param>
        /// <param name="maxRetries">Maximum number of connection retry attempts</param>
        /// <param name="retryDelay">Delay after connection retry in milliseconds</param>
        protected Connection(string address, TcpExChannel channel, bool keepAlive, ulong keepAliveTime, ulong KeepAliveInterval, short maxRetries, int retryDelay)
        {
            if (string.IsNullOrEmpty(address))
            {
                throw new ArgumentException(LanguageResource.ArgumentException_AddressMustNotBeEmpty, "address");
            }

            if (channel == null)
            {
                throw new ArgumentNullException("channel");
            }

            _connectionRole = ConnectionRole.ActAsClient;
            _maxRetries     = maxRetries;
            _retryDelay     = retryDelay;
            _channel        = channel;

            Match m = _addressRegEx.Match(address);

            if (!m.Success)
            {
                throw new FormatException(string.Format(LanguageResource.Format_Exception_InvalidAddressFormat, address));
            }

            IPAddress remoteIPAddress = Manager.GetHostByName(m.Groups["address"].Value);

            _socketRemoteAddress = remoteIPAddress.ToString();
            _socketRemotePort    = int.Parse(m.Groups["port"].Value);

            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _socket.Connect(new IPEndPoint(remoteIPAddress, _socketRemotePort));

            CheckSocket();

            if (!SendChannelInfo())
            {
                throw new RemotingException(LanguageResource.RemotingException_ErrorSendingChannelInfo);
            }

            if (!ReceiveChannelInfo())
            {
                throw new RemotingException(LanguageResource.RemotingException_ErrorReceivingChannelInfo);
            }

            if (_connections.ContainsKey(_remoteChannelData.ChannelID.ToString()))
            {
                _socket.Close();
                throw new DuplicateConnectionException(_remoteChannelData.ChannelID);
            }
            TcpKeepAliveTime     = keepAliveTime;
            TcpKeepAliveInterval = KeepAliveInterval;
            TcpKeepAliveEnabled  = keepAlive;

            AddToConnectionList();
        }
Пример #8
0
        /// <summary>
        /// Creates a connection object.
        /// </summary>
        /// <param name="socket">Connection socket</param>
        /// <param name="channel">Connection channel</param>
        /// <param name="keepAlive">Enables or disables TCP KeepAlive for the new connection</param>
        /// <param name="keepAliveTime">Time for TCP KeepAlive in Milliseconds</param>
        /// <param name="KeepAliveInterval">Interval for TCP KeepAlive in Milliseconds</param>
        /// <param name="maxRetries">Maximum number of connection retry attempts</param>
        /// <param name="retryDelay">Delay after connection retry in milliseconds</param>
        /// <returns>Connection</returns>
        public static Connection CreateConnection(Socket socket, TcpExChannel channel, bool keepAlive, ulong keepAliveTime, ulong KeepAliveInterval, short maxRetries, int retryDelay)
        {
            if (socket == null)
            {
                throw new ArgumentNullException("socket");
            }

            if (channel == null)
            {
                throw new ArgumentNullException("channel");
            }

            return(new Connection(socket, channel, keepAlive, keepAliveTime, KeepAliveInterval, maxRetries, retryDelay));
        }
Пример #9
0
        public ClientTransportSink(string server, TcpExChannel channel)
        {
            Debug.Assert(server != null);

            this.server = server;
            this.channel = channel;

            if (channel.ConnectDuringCreation)
            {
                // Try to connect so we fail during creation if the other side isn't listening
                Connection.GetConnection(server, channel, channel.TcpKeepAliveEnabled, channel.TcpKeepAliveTime,
                    channel.TcpKeepAliveInterval, channel.MaxRetries, channel.RetryDelay);
            }
        }
Пример #10
0
        /// <summary>
        /// Get all currently running connection of a specified channel.
        /// </summary>
        /// <param name="channel">TcpEx Channel</param>
        /// <returns>Running connections</returns>
        internal static IEnumerable <Connection> GetRunningConnectionsOfChannel(TcpExChannel channel)
        {
            if (channel == null)
            {
                throw new ArgumentNullException("channel");
            }

            lock (_connectionsLockObject)
            {
                return(from connection in _connections.Values
                       where connection._channel.ChannelID.Equals(channel.ChannelID)
                       select connection);
            }
        }
Пример #11
0
        public ClientTransportSink(string server, TcpExChannel channel)
        {
            Debug.Assert(server != null);

            this.server  = server;
            this.channel = channel;

            if (channel.ConnectDuringCreation)
            {
                // Try to connect so we fail during creation if the other side isn't listening
                Connection.GetConnection(server, channel, channel.TcpKeepAliveEnabled, channel.TcpKeepAliveTime,
                                         channel.TcpKeepAliveInterval, channel.MaxRetries, channel.RetryDelay);
            }
        }
Пример #12
0
        public static Socket StartListening(int port, TcpExChannel channel, IPAddress bindToAddress)
        {
            if (bindToAddress == null)
            {
                throw new ArgumentNullException("bindToAddress");
            }

            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            listener.Bind(new IPEndPoint(bindToAddress, port));
            listener.Listen(1000);
            listener.BeginAccept(new AsyncCallback(listener_Accept), new object[] { listener, channel });

            return(listener);
        }
Пример #13
0
        /// <summary>
        /// Creates a new instance of the TcpExChannelData class.
        /// </summary>
        /// <param name="channel">Remoting channel</param>
        public TcpExChannelData(TcpExChannel channel)
        {
            Port = channel.Port;
            ChannelID = channel.ChannelID;

            if (Port != 0)
            {
                Addresses = new List<string>();
                IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());

                foreach (IPAddress address in hostEntry.AddressList)
                {
                    Addresses.Add(string.Format("{0}:{1}", address, Port));
                }
            }
        }
Пример #14
0
        /// <summary>
        /// Creates a new instance of the TcpExChannelData class.
        /// </summary>
        /// <param name="channel">Remoting channel</param>
        public TcpExChannelData(TcpExChannel channel)
        {
            Port      = channel.Port;
            ChannelID = channel.ChannelID;

            if (Port != 0)
            {
                Addresses = new List <string>();
                IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());

                foreach (IPAddress address in hostEntry.AddressList)
                {
                    Addresses.Add(string.Format("{0}:{1}", address, Port));
                }
            }
        }
Пример #15
0
        /// <summary>
        /// Stops listening of a specified channel.
        /// </summary>
        /// <param name="channel">TcpEx Channel</param>
        public static void StopListening(TcpExChannel channel)
        {
            if (channel == null)
            {
                throw new ArgumentNullException("channel");
            }

            var runningConnections = Connection.GetRunningConnectionsOfChannel(channel);

            if (runningConnections != null)
            {
                while (runningConnections.Count() > 0)
                {
                    runningConnections.First().Close();
                }
            }
        }
Пример #16
0
        /// <summary>
        /// Creates a new instance of the Connection class.
        /// </summary>
        /// <param name="socket">Socket which sould be used</param>
        /// <param name="channel">Remoting channel</param>
        /// <param name="keepAlive">Enables or disables TCP KeepAlive for the new connection</param>
        /// <param name="keepAliveTime">Time for TCP KeepAlive in Milliseconds</param>
        /// <param name="KeepAliveInterval">Interval for TCP KeepAlive in Milliseconds</param>
        /// <param name="maxRetries">Maximum number of connection retry attempts</param>
        /// <param name="retryDelay">Delay after connection retry in milliseconds</param>
        protected Connection(Socket socket, TcpExChannel channel, bool keepAlive, ulong keepAliveTime, ulong KeepAliveInterval, short maxRetries, int retryDelay)
        {
            if (socket == null)
            {
                throw new ArgumentNullException("socket");
            }

            if (channel == null)
            {
                throw new ArgumentNullException("channel");
            }

            _connectionRole = ConnectionRole.ActAsServer;
            _maxRetries     = maxRetries;
            _retryDelay     = retryDelay;
            _channel        = channel;
            _socket         = socket;

            IPEndPoint remoteEndPoint = socket.RemoteEndPoint as IPEndPoint;

            _socketRemoteAddress = remoteEndPoint.Address.ToString();
            _socketRemotePort    = remoteEndPoint.Port;

            CheckSocket();

            if (!ReceiveChannelInfo())
            {
                throw new RemotingException(LanguageResource.RemotingException_ErrorReceivingChannelInfo);
            }

            if (!SendChannelInfo())
            {
                throw new RemotingException(LanguageResource.RemotingException_ErrorSendingChannelInfo);
            }

            if (_connections.ContainsKey(_remoteChannelData.ChannelID.ToString()))
            {
                socket.Close();
                throw new DuplicateConnectionException(_remoteChannelData.ChannelID);
            }
            TcpKeepAliveTime     = keepAliveTime;
            TcpKeepAliveInterval = KeepAliveInterval;
            TcpKeepAliveEnabled  = keepAlive;

            AddToConnectionList();
        }
Пример #17
0
        /// <summary>
        /// Unregisters all running connections of the specified <see cref="TcpExChannel"/>.
        /// </summary>
        /// <param name="channel">TcpEx Channel</param>
        internal static void UnregisterConnectionsOfChannel(TcpExChannel channel)
        {
            if (channel == null)
            {
                throw new ArgumentNullException("channel");
            }

            lock (_connectionsLockObject)
            {
                var toBeDeleted =
                    from pair in _connections
                    where pair.Value._channel.ChannelID.Equals(channel.ChannelID)
                    select pair.Key;

                foreach (string key in toBeDeleted.ToArray())
                {
                    _connections.Remove(key);
                }
            }
        }
Пример #18
0
        /// <summary>
        /// Closes the connection.
        /// </summary>
        public void Close()
        {
            lock (_connectionsLockObject)
            {
                var toBeDeleted =
                    from pair in _connections
                    where pair.Value == this
                    select pair.Key;

                foreach (string key in toBeDeleted.ToList())
                {
                    _connections.Remove(key);
                }
            }

            LockRead();
            LockWrite();

            _socketRemoteAddress = null;
            _socketRemotePort    = 0;

            if (_reader != null)
            {
                try
                {
                    _reader.Close();
                }
                catch (ObjectDisposedException)
                {
                }
                finally
                {
                    _reader = null;
                }
            }

            if (_writer != null)
            {
                try
                {
                    _writer.Close();
                }
                catch (ObjectDisposedException)
                {
                }
                finally
                {
                    _writer = null;
                }
            }

            if (_stream != null)
            {
                try
                {
                    _stream.Close();
                }
                catch (ObjectDisposedException)
                {
                }
                finally
                {
                    _stream = null;
                }
            }

            if (_socket != null)
            {
                try
                {
                    _socket.Shutdown(SocketShutdown.Both);
                    _socket.Close();
                }
                catch (SocketException)
                {
                }
                catch (ObjectDisposedException)
                {
                }
                finally
                {
                    _socket = null;
                }
            }

            if (_channel != null)
            {
                _channel = null;
            }

            if (_remoteChannelData != null)
            {
                _remoteChannelData = null;
            }

            ReleaseRead();
            ReleaseWrite();

            _isClosed = true;
        }
Пример #19
0
		/// <summary>
		/// Stops listening of a specified channel.
		/// </summary>
		/// <param name="channel">TcpEx Channel</param>
		/// <param name="listenerAddresses">Addresses the channel is listening</param>
		public static void StopListening(TcpExChannel channel, string[] listenerAddresses)
		{
			if (channel == null)
				throw new ArgumentNullException("channel");

			// close running connections
			var runningConnections = Connection.GetRunningConnectionsOfChannel(channel);
			if (runningConnections != null)
			{
				while (runningConnections.Count()>0)
				{
					runningConnections.First().Close();
				}
			}

			// remove pending listeners if specified
			if (listenerAddresses != null)
			{
				lock (_listenersLockObject)
				{
					foreach (var address in listenerAddresses)
						_listeners.Remove(address);
				}
			}
		}
Пример #20
0
        /// <summary>
        /// Unregisters all running connections of the specified <see cref="TcpExChannel"/>.
        /// </summary>
        /// <param name="channel">TcpEx Channel</param>
        internal static void UnregisterConnectionsOfChannel(TcpExChannel channel)
        {
            if (channel == null)
                throw new ArgumentNullException("channel");

            lock (_connectionsLockObject)
            {
                var toBeDeleted =
                    from pair in _connections
                    where pair.Value._channel.ChannelID.Equals(channel.ChannelID)
                    select pair.Key;

                foreach (string key in toBeDeleted.ToArray())
                {
                    _connections.Remove(key);
                }
            }
        }
Пример #21
0
        /// <summary>
        /// Get all currently running connection of a specified channel.
        /// </summary>
        /// <param name="channel">TcpEx Channel</param>
        /// <returns>Running connections</returns>
        internal static IEnumerable<Connection> GetRunningConnectionsOfChannel(TcpExChannel channel)
        {
            if (channel == null)
                throw new ArgumentNullException("channel");

            lock (_connectionsLockObject)
            {
                return from connection in _connections.Values
                    where connection._channel.ChannelID.Equals(channel.ChannelID)
                    select connection;
            }
        }
Пример #22
0
        /// <summary>
        /// Closes the connection.
        /// </summary>
        public void Close()
        {
            lock (_connectionsLockObject)
            {
                List<string> toBeDeleted = (from pair in _connections
                                            where pair.Value == this
                                            select pair.Key).ToList();

                foreach (string key in toBeDeleted)
                {
                    _connections.Remove(key);
                }
            }
            LockRead();
            LockWrite();

            _socketRemoteAddress = null;
            _socketRemotePort = 0;

            if (_reader != null)
            {
                try
                {
                    _reader.Close();
                }
                catch (ObjectDisposedException)
                {
                }
                finally
                {
                    _reader = null;
                }
            }
            if (_writer != null)
            {
                try
                {
                    _writer.Close();
                }
                catch (ObjectDisposedException)
                {
                }
                finally
                {
                    _writer = null;
                }
            }
            if (_stream != null)
            {
                try
                {
                    _stream.Close();
                }
                catch (ObjectDisposedException)
                {
                }
                finally
                {
                    _stream = null;
                }
            }
            if (_socket != null)
            {
                try
                {
                    _socket.Close();
                }
                catch (ObjectDisposedException)
                {
                }
                finally
                {
                    _socket = null;
                }
            }
            if (_channel != null)
                _channel = null;

            if (_remoteChannelData != null)
                _remoteChannelData = null;

            ReleaseRead();
            ReleaseWrite();

            _isClosed = true;
        }
Пример #23
0
        /// <summary>
        /// Gets a specified connection.
        /// </summary>
        /// <param name="address">Address of the connection</param>
        /// <param name="channel">Channel of the connection</param>
        /// <param name="keepAlive">Enables or disables TCP KeepAlive for the new connection</param>
        /// <param name="keepAliveTime">Time for TCP KeepAlive in Milliseconds</param>
        /// <param name="KeepAliveInterval">Interval for TCP KeepAlive in Milliseconds</param>
        /// <param name="maxRetries">Maximum number of connection retry attempts</param>
        /// <param name="retryDelay">Delay after connection retry in milliseconds</param>
        /// <returns>Connection</returns>
        public static Connection GetConnection(string address, TcpExChannel channel, bool keepAlive, ulong keepAliveTime, ulong KeepAliveInterval, short maxRetries, int retryDelay)
        {
            if (string.IsNullOrEmpty(address))
                throw new ArgumentException(LanguageResource.ArgumentException_AddressMustNotBeEmpty, "address");

            if (channel == null)
                throw new ArgumentNullException("channel");

            Trace.WriteLine("TcpEx.Connection.GetConnection: {0}", address);

            lock (_connectionsLockObject)
            {
                if (_connections.ContainsKey(address))
                {
                    var foundConnection = _connections[address];
                    Trace.WriteLine("TcpEx.Connection found. ChannelID: {0}", foundConnection._channel.ChannelID);

                    if (foundConnection.IsClosed)
                        _connections.Remove(address);
                    else
                        return foundConnection;
                }

                Connection connection = null;

                try
                {
                    Trace.WriteLine("TcpEx.Connection is created...");

                    connection = new Connection(address, channel, keepAlive, keepAliveTime, KeepAliveInterval, maxRetries, retryDelay);
                    if (!_connections.ContainsKey(address))
                        _connections.Add(address, connection); // This most often happens when using the loopback address

                    Manager.StartListening(connection);
                }
                catch (DuplicateConnectionException ex)
                {
                    connection = _connections[ex.ChannelID.ToString()];
                    _connections.Add(address, connection);
                }
                catch (FormatException formatEx)
                {
                    throw new RemotingException(string.Format(LanguageResource.RemotingException_ConnectionError, formatEx.Message), formatEx);
                }

                return connection;
            }
        }
Пример #24
0
        /// <summary>
        /// Creates a connection object.
        /// </summary>
        /// <param name="socket">Connection socket</param>
        /// <param name="channel">Connection channel</param>
        /// <param name="keepAlive">Enables or disables TCP KeepAlive for the new connection</param>
        /// <param name="keepAliveTime">Time for TCP KeepAlive in Milliseconds</param>
        /// <param name="KeepAliveInterval">Interval for TCP KeepAlive in Milliseconds</param>
        /// <param name="maxRetries">Maximum number of connection retry attempts</param>
        /// <param name="retryDelay">Delay after connection retry in milliseconds</param>
        /// <returns>Connection</returns>
        public static Connection CreateConnection(Socket socket, TcpExChannel channel, bool keepAlive, ulong keepAliveTime, ulong KeepAliveInterval, short maxRetries, int retryDelay)
        {
            if (socket==null)
                throw new ArgumentNullException("socket");

            if (channel == null)
                throw new ArgumentNullException("channel");

            return new Connection(socket, channel, keepAlive, keepAliveTime, KeepAliveInterval, maxRetries, retryDelay);
        }
Пример #25
0
        /// <summary>
        /// Creates a new instance of the Connection class.
        /// </summary>
        /// <param name="socket">Socket which sould be used</param>
        /// <param name="channel">Remoting channel</param>
        /// <param name="keepAlive">Enables or disables TCP KeepAlive for the new connection</param>
        /// <param name="keepAliveTime">Time for TCP KeepAlive in Milliseconds</param>
        /// <param name="KeepAliveInterval">Interval for TCP KeepAlive in Milliseconds</param>
        /// <param name="maxRetries">Maximum number of connection retry attempts</param>
        /// <param name="retryDelay">Delay after connection retry in milliseconds</param>
        protected Connection(Socket socket, TcpExChannel channel, bool keepAlive, ulong keepAliveTime, ulong KeepAliveInterval, short maxRetries, int retryDelay)
        {
            if (socket == null)
                throw new ArgumentNullException("socket");

            if (channel == null)
                throw new ArgumentNullException("channel");

            _connectionRole = ConnectionRole.ActAsServer;
            _maxRetries = maxRetries;
            _retryDelay = retryDelay;
            _channel = channel;
            _socket = socket;

            IPEndPoint remoteEndPoint = socket.RemoteEndPoint as IPEndPoint;
            _socketRemoteAddress = remoteEndPoint.Address.ToString();
            _socketRemotePort = remoteEndPoint.Port;

            CheckSocket();

            if (!ReceiveChannelInfo())
                throw new RemotingException(LanguageResource.RemotingException_ErrorReceivingChannelInfo);

            if (!SendChannelInfo())
                throw new RemotingException(LanguageResource.RemotingException_ErrorSendingChannelInfo);

            if (_connections.ContainsKey(_remoteChannelData.ChannelID.ToString()))
            {
                socket.Close();
                throw new DuplicateConnectionException(_remoteChannelData.ChannelID);
            }
            TcpKeepAliveTime = keepAliveTime;
            TcpKeepAliveInterval = KeepAliveInterval;
            TcpKeepAliveEnabled = keepAlive;

            AddToConnectionList();
        }
Пример #26
0
        /// <summary>
        /// Creates a new instance of the Connection class.
        /// </summary>
        /// <param name="address">Address (IP oder DNS based)</param>
        /// <param name="channel">Remoting channel</param>
        /// <param name="keepAlive">Enables or disables TCP KeepAlive for the new connection</param>
        /// <param name="keepAliveTime">Time for TCP KeepAlive in Milliseconds</param>
        /// <param name="KeepAliveInterval">Interval for TCP KeepAlive in Milliseconds</param>
        /// <param name="maxRetries">Maximum number of connection retry attempts</param>
        /// <param name="retryDelay">Delay after connection retry in milliseconds</param>
        protected Connection(string address, TcpExChannel channel, bool keepAlive, ulong keepAliveTime, ulong KeepAliveInterval, short maxRetries, int retryDelay)
        {
            if (string.IsNullOrEmpty(address))
                throw new ArgumentException(LanguageResource.ArgumentException_AddressMustNotBeEmpty, "address");

            if (channel == null)
                throw new ArgumentNullException("channel");

            _connectionRole = ConnectionRole.ActAsClient;
            _maxRetries = maxRetries;
            _retryDelay = retryDelay;
            _channel = channel;

            Match m = _addressRegEx.Match(address);

            if (!m.Success)
                throw new FormatException(string.Format(LanguageResource.Format_Exception_InvalidAddressFormat, address));

            IPAddress remoteIPAddress = Manager.GetHostByName(m.Groups["address"].Value);
            _socketRemoteAddress = remoteIPAddress.ToString();
            _socketRemotePort = int.Parse(m.Groups["port"].Value);

            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _socket.Connect(new IPEndPoint(remoteIPAddress, _socketRemotePort));

            CheckSocket();

            if (!SendChannelInfo())
                throw new RemotingException(LanguageResource.RemotingException_ErrorSendingChannelInfo);

            if (!ReceiveChannelInfo())
                throw new RemotingException(LanguageResource.RemotingException_ErrorReceivingChannelInfo);

            if (_connections.ContainsKey(_remoteChannelData.ChannelID.ToString()))
            {
                _socket.Close();
                throw new DuplicateConnectionException(_remoteChannelData.ChannelID);
            }
            TcpKeepAliveTime = keepAliveTime;
            TcpKeepAliveInterval = KeepAliveInterval;
            TcpKeepAliveEnabled = keepAlive;

            AddToConnectionList();
        }
Пример #27
0
		public static int StartListening(int port, TcpExChannel channel, IPAddress bindToAddress)
		{
			if (bindToAddress == null)
				throw new ArgumentNullException("bindToAddress");

			Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			listener.Bind(new IPEndPoint(bindToAddress, port));
			listener.Listen(1000);
			listener.BeginAccept(new AsyncCallback(listener_Accept), new object[] {listener, channel});

			return ((IPEndPoint)listener.LocalEndPoint).Port;
		}
Пример #28
0
		/// <summary>
		/// Stops listening of a specified channel.
		/// </summary>
		/// <param name="channel">TcpEx Channel</param>
		public static void StopListening(TcpExChannel channel)
		{
			if (channel == null)
				throw new ArgumentNullException("channel");

			var runningConnections = Connection.GetRunningConnectionsOfChannel(channel);

			if (runningConnections != null)
			{
				while(runningConnections.Count()>0)
				{
					runningConnections.First().Close();
				}
			}
		}