Exemple #1
0
        /// <summary>
        /// Initializing server.
        /// </summary>
        /// <param name="ip">If ip null or empty, it will using loopback address. If ip setting as *, it will use any address in network.</param>
        public BasicTcpServer(string ip, int port, TcpSettings tcpSettings = null)
        {
            IPAddress _IPAddress;

            if (string.IsNullOrEmpty(ip))
            {
                _IPAddress = IPAddress.Loopback;
            }
            else if (ip == "*")
            {
                _IPAddress = IPAddress.Any;
            }
            else
            {
                if (!IPAddress.TryParse(ip, out _IPAddress))
                {
                    _IPAddress = Dns.GetHostEntry(ip).AddressList[0];
                }
            }

            TcpSettings = tcpSettings;

            if (TcpSettings == null)
            {
                TcpSettings = new TcpSettings(600000, 600000);
            }

            _Listener = new TcpListener(_IPAddress, port);
            _Listener.Server.SendTimeout    = TcpSettings.SendTimeout;
            _Listener.Server.ReceiveTimeout = TcpSettings.ReceiveTimeout;

            TcpSettings.Socket = _Listener.Server;

            _Token = _TokenSource.Token;
        }
Exemple #2
0
        /// <summary>
        /// Initializing TCP client.
        /// </summary>
        /// <param name="autoReconnectTime">Time to reconnect to server in MS. Disabled if set to 0.</param>
        public BasicTcpClient(string ip, int port, uint autoReconnectTime = 0, TcpSettings tcpSettings = null)
        {
            if (string.IsNullOrEmpty(ip))
            {
                throw new ArgumentNullException(nameof(ip));
            }
            if (port < 0)
            {
                throw new ArgumentException("Port must be zero or greater.");
            }

            try
            {
                _AutoReconnectTime = autoReconnectTime;

                if (!IPAddress.TryParse(ip, out _IPAddress))
                {
                    _IPAddress = Dns.GetHostEntry(ip).AddressList[0];
                }

                _Port = port;

                TcpSettings = tcpSettings;

                if (TcpSettings == null)
                {
                    TcpSettings = new TcpSettings(600000, 600000);
                }

                _Client = new TcpClient
                {
                    ReceiveTimeout = TcpSettings.ReceiveTimeout,
                    SendTimeout    = TcpSettings.SendTimeout
                };
                _Token = _TokenSource.Token;

                TcpSettings.TcpClient = _Client;

                _IsInitialized = true;
            }
            catch (Exception ex)
            {
                if (autoReconnectTime != 0)
                {
                    StartAutoReconnect();
                }
                else
                {
                    throw ex;
                }
            }
        }