Esempio n. 1
0
        public void HostNameReturnIpEndPointWithInternetworkV6AddressFamily()
        {
            var address    = Dns.GetHostName();
            var ipEndPoint = IpEndPointParser.Parse(address, _port);

            Assert.IsTrue(ipEndPoint.AddressFamily == AddressFamily.InterNetworkV6);
        }
Esempio n. 2
0
        public void Pv6StringReturnIpEndPointWithInternetworkV6AddressFamily()
        {
            var address    = "::1";
            var ipEndPoint = IpEndPointParser.Parse(address, _port);

            Assert.IsTrue(ipEndPoint.AddressFamily == AddressFamily.InterNetworkV6);
        }
Esempio n. 3
0
        private static void Main(string[] args)
        {
            TaskManager taskManager;

            try
            {
                var config = ComponentConfigurationSection.LoadConfig("componentConfig", args);

                var serverAddress = IpEndPointParser.Parse(config.PrimaryServer.Address, config.PrimaryServer.Port);
                var taskSolversDirectoryRelativePath = config.TaskSolversPath;

                _logger.Info("Server address: " + serverAddress);

                ThreadManager threadManager = new ThreadPoolThreadManager();
                taskManager = new TaskManager(threadManager, serverAddress, taskSolversDirectoryRelativePath);
            }
            catch (Exception ex)
            {
                var errorText = string.Format("{0}:{1}", ex.GetType().FullName, ex.Message);
                if (ex.InnerException != null)
                {
                    errorText += string.Format("|({0}:{1})", ex.InnerException.GetType().FullName,
                                               ex.InnerException.Message);
                }
                _logger.Error(errorText);
                return;
            }

            taskManager.MessageEnqueuedToSend    += taskManager_MessageEnqueuedToSend;
            taskManager.MessageSent              += taskManager_MessageSent;
            taskManager.MessageReceived          += taskManager_MessageReceived;
            taskManager.MessageHandlingException += taskManager_MessageHandlingException;
            taskManager.MessageSendingException  += taskManager_MessageSendingException;

            taskManager.OnStarting += taskManager_OnStarting;
            taskManager.OnStarted  += taskManager_OnStarted;


            taskManager.Start();
            string line;

            while (true)
            {
                line = Console.ReadLine().ToLower();
                if (line == "stop" || line == "quit" || line == "exit")
                {
                    break;
                }
                if (line == "start")
                {
                    taskManager.Start();
                }
                if (line == "running")
                {
                    Console.WriteLine("TaskManager.IsRunning={0}", taskManager.IsRunning);
                }
            }
        }
Esempio n. 4
0
        private static void Main(string[] args)
        {
            CommunicationServer communicationServer;

            try
            {
                var config = ServerConfigurationSection.LoadConfig("serverConfig", args);

                var serverAddress = IpEndPointParser.Parse(config.Address, config.Port);
                var timeout       = config.Timeout;
                var isBackup      = config.IsBackup;

                IPEndPoint masterServerAddress;
                if (isBackup)
                {
                    masterServerAddress = IpEndPointParser.Parse(config.MasterServer.Address, config.MasterServer.Port);
                }

                //_logger.Info("Server address: " + serverAddress);

                var serverConfig = new ServerConfig
                {
                    Mode    = isBackup ? ServerConfig.ServerMode.Backup : ServerConfig.ServerMode.Primary,
                    Address = serverAddress,
                    CommunicationTimeout = timeout
                };

                communicationServer = new CommunicationServer(serverConfig);
            }
            catch (Exception ex)
            {
                var errorText = string.Format("{0}:{1}", ex.GetType().FullName, ex.Message);
                if (ex.InnerException != null)
                {
                    errorText += string.Format("|({0}:{1})", ex.InnerException.GetType().FullName,
                                               ex.InnerException.Message);
                }
                //_logger.Error(errorText);
                return;
            }

            communicationServer.Start();

            while (Console.ReadLine() != "exit")
            {
                // input handling
            }

            communicationServer.Stop();
        }
Esempio n. 5
0
        /// <summary>
        ///     Sends messages and returns messages received. Retruns null if neither primary nor backup servers answered or due to
        ///     other exception.
        /// </summary>
        /// <param name="messages">Messages to send.</param>
        /// <returns>Messages returned or null.</returns>
        public List <Message> Send(IList <Message> messages)
        {
            var data = _marshaller.Marshall(messages);

            byte[] retBytes = null;
            bool   again;

            do
            {
                try
                {
                    again    = false;
                    retBytes = _tcpClient.SendData(data);
                }
                catch (TimeoutException)
                {
                    again = true;
                    if (_servers.Count > 0)
                    {
                        try
                        {
                            _tcpClient.ServerAddress = IpEndPointParser.Parse(_servers[0].IpAddress, _servers[0].Port);
                        }
                        catch (Exception)
                        {
                            // just skip incorrect address
                        }

                        _servers.RemoveAt(0);
                    }
                    else
                    {
                        //No servers available
                        return(null);
                    }
                }
                catch (Exception)
                {
                    //can not send to server
                    return(null);
                }
            } while (again);


            var messagesReceived = _marshaller.Unmarshall(retBytes);

            UpdateServerList(messagesReceived);
            return(retBytes != null ? messagesReceived : null);
        }
Esempio n. 6
0
        private static void Main(string[] args)
        {
            ComputationalClient computationalClient;

            try
            {
                var config = ComponentConfigurationSection.LoadConfig("componentConfig", args);

                var serverAddress = IpEndPointParser.Parse(config.PrimaryServer.Address, config.PrimaryServer.Port);
                //string taskSolversDirectoryRelativePath = config.TaskSolversPath;

                Logger.Info("Server address: " + serverAddress);

                computationalClient = new ComputationalClient(serverAddress);
            }
            catch (Exception ex)
            {
                var errorText = string.Format("{0}:{1}", ex.GetType().FullName, ex.Message);
                if (ex.InnerException != null)
                {
                    errorText += string.Format("|({0}:{1})", ex.InnerException.GetType().FullName,
                                               ex.InnerException.Message);
                }
                Logger.Error(errorText);
                return;
            }

            computationalClient.MessageSent              += computationalClient_MessageSent;
            computationalClient.MessageReceived          += computationalClient_MessageReceived;
            computationalClient.MessageSendingException  += computationalClient_MessageSendingException;
            computationalClient.MessageHandlingException += computationalClient_MessageHandlingException;

            string line;

            while (true)
            {
                Console.WriteLine(@"commands: -stop, quit, exit -solve -solution");

                line = Console.ReadLine();
                if (line != null)
                {
                    line = line.ToLower();
                }
                else
                {
                    continue;
                }

                switch (line)
                {
                case "stop":
                case "quit":
                case "exit":
                    return;

                case "solve":
                    Console.WriteLine(@"File name that contains the problem: ");
                    line = Console.ReadLine();
                    if (line == null)
                    {
                        goto case "solve";
                    }
                    byte[] problemData;
                    try
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            var formatter = new BinaryFormatter();
                            formatter.Serialize(memoryStream, File.ReadAllText(line, Encoding.UTF8));
                            problemData = memoryStream.ToArray();
                        }
                    }
                    catch (Exception)
                    {
                        Console.WriteLine(@"Wrong file!");
                        continue;
                    }
                    Console.WriteLine(@"Timeout in seconds: ");
                    ulong timeout;
                    if (!ulong.TryParse(Console.ReadLine(), out timeout))
                    {
                        timeout = (ulong)TimeSpan.MaxValue.TotalSeconds;
                    }
                    Console.WriteLine(@"Problem type (for example 'dvrp'): ");
                    line = Console.ReadLine();
                    if (line == null)
                    {
                        goto case "solve";
                    }
                    line = line.ToLower();
                    if (line == "dvrp")
                    {
                        var problemType = "UCC.Dvrp";
                        computationalClient.SendSolveRequest(problemType, problemData, timeout);
                    }
                    break;

                case "solution":
                    Console.Write(@"Enter problem id: ");
                    ulong id;
                    if (ulong.TryParse(Console.ReadLine(), out id))
                    {
                        var solutionsMessages = computationalClient.SendSolutionRequest(id);
                        if (solutionsMessages != null && solutionsMessages.Count > 0)
                        {
                            switch (solutionsMessages[0].Solutions[0].Type)
                            {
                            case SolutionsMessage.SolutionType.Ongoing:
                                Console.WriteLine(@"Server is still solving the problem");
                                break;

                            case SolutionsMessage.SolutionType.Partial:
                            case SolutionsMessage.SolutionType.Final:
                                string problem;
                                using (var mem = new MemoryStream(solutionsMessages[0].Solutions[0].Data))
                                {
                                    var formatter = new BinaryFormatter();
                                    problem = (string)formatter.Deserialize(mem);
                                }
                                Console.WriteLine(@"Result message: {0}", problem);
                                break;

                            default:
                                throw new ArgumentOutOfRangeException();
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine(@"Parsing error!");
                    }
                    break;
                }
            }
        }
Esempio n. 7
0
        public async Task ConnectAsync()
        {
            AssertInitParams();
            if (IsConnected)
            {
                throw new InvalidOperationException($"{GetType().Name} уже подключен к устройству");
            }
            if (!IpEndPointParser.TryParse(_config.BedIpEndpoint, out _bedIpEndPoint))
            {
                throw new ArgumentException("Не верно указан адрес подключения к кровати. Требуемый формат - ip:port");
            }

            try
            {
                // очистим перед подключением все накопленные ошибки
                while (_lastExceptions.TryDequeue(out _))
                {
                }

                await InternalDisconectAsync().ConfigureAwait(false);

                _udpSendingClient = new UdpClient
                {
                    Client =
                    {
                        ReceiveTimeout = (int)_config.Timeout.TotalMilliseconds,
                        SendTimeout    = (int)_config.Timeout.TotalMilliseconds
                    }
                };

                _udpReceivingClient = new UdpClient(_bedIpEndPoint.Port)
                {
                    Client =
                    {
                        ReceiveTimeout = (int)_config.Timeout.TotalMilliseconds,
                        SendTimeout    = (int)_config.Timeout.TotalMilliseconds
                    }
                };
                _udpSendingClient.Connect(_bedIpEndPoint);
                _udpReceivingClient.Connect(_bedIpEndPoint);

                IsConnected = true;
                await UpdateRegistersValueAsync()
                .ConfigureAwait(false);

                _syncWorker = _workerController.StartWorker(_config.UpdateDataPeriod, async() =>
                {
                    if (_initialisingStatus == DeviceIsInitialising)
                    {
                        return;
                    }

                    try
                    {
                        //todo сюды бы токен отмены
                        await UpdateRegistersValueAsync()
                        .ConfigureAwait(false);
                    }
                    catch (Exception e)
                    {
                        IsConnected = false;
                        _workerController.CloseWorker(_syncWorker);
                        _lastExceptions.Enqueue(e);
                    }
                });
            }
            catch (DeviceConnectionException)
            {
                IsConnected = false;
                throw;
            }
            catch (SocketException e)
            {
                IsConnected = false;
                throw new DeviceConnectionException("Ошибка подключения к инверсионному столу", e);
            }
            catch (ObjectDisposedException e)
            {
                IsConnected = false;
                throw new DeviceConnectionException("Ошибка подключения к инверсионному столу", e);
            }
            catch (Exception e)
            {
                IsConnected = false;
                throw new DeviceProcessingException("Ошибка в ходе обработки данных от инверсионного стола", e);
            }
        }