예제 #1
0
 public ServiceSubscriber(string host, int port)
 {
     this.m_Communicator = new TcpCommunicator <BoxedObject>(host, port);
     this.m_Communicator.DispatchMessageInEvent = true;
     this.m_Communicator.MessageReceived       += M_Communicator_MessageReceived;
     this.m_Communicator.Connect();
 }
 /// <summary>
 /// Освобождение ресурсов
 /// </summary>
 public override void Dispose()
 {
     if (_communicator != null)
     {
         _communicator.Dispose();
         _communicator = null;
     }
 }
예제 #3
0
        public void MultipleTcpComTest()
        {
            EnvelopeQueue inQA  = new EnvelopeQueue();
            EnvelopeQueue outQA = new EnvelopeQueue();
            EnvelopeQueue inQB  = new EnvelopeQueue();
            EnvelopeQueue outQB = new EnvelopeQueue();
            EnvelopeQueue inQC  = new EnvelopeQueue();
            EnvelopeQueue outQC = new EnvelopeQueue();

            //Create the communicators
            TcpCommunicator tcpComA = new TcpCommunicator(inQA, outQA, new IPEndPoint(IPAddress.Loopback, 0));
            TcpCommunicator tcpComB = new TcpCommunicator(inQB, outQB, new IPEndPoint(IPAddress.Loopback, 0));
            TcpCommunicator tcpComC = new TcpCommunicator(inQC, outQC, new IPEndPoint(IPAddress.Loopback, 0));

            //start communicator threads
            tcpComA.startThreads();
            tcpComB.startThreads();
            tcpComC.startThreads();

            //Create a messages to send.
            AssignIdMessage messAToB      = new AssignIdMessage(5, new byte[] { 0x1, 0x3 }, new byte[] { 0x1, 0x2 }, new Identifier(1, 1), new Identifier(1, 1));
            AssignIdMessage messAToC      = new AssignIdMessage(5, new byte[] { 0x1, 0x3 }, new byte[] { 0x1, 0x2 }, new Identifier(1, 2), new Identifier(1, 2));
            AssignIdMessage messAToBAgain = new AssignIdMessage(5, new byte[] { 0x1, 0x3 }, new byte[] { 0x1, 0x2 }, new Identifier(1, 3), new Identifier(1, 3));

            //Create Envelopes
            Envelope env1 = new Envelope(messAToB, tcpComA.getListenerEndPoint(), tcpComB.getListenerEndPoint(), true);
            Envelope env2 = new Envelope(messAToC, tcpComA.getListenerEndPoint(), tcpComC.getListenerEndPoint(), true);
            Envelope env3 = new Envelope(messAToBAgain, tcpComA.getListenerEndPoint(), tcpComB.getListenerEndPoint(), true);

            //Send Envelopes
            outQA.Enqueue(env1);
            outQA.Enqueue(env2);
            outQA.Enqueue(env3);

            //wait for messages.
            Thread.Sleep(5000);

            //Make sure message were recieved.
            Assert.IsTrue(inQB.Count == 2);
            Assert.IsTrue(inQC.Count == 1);

            //Check the envelopes
            Envelope env;

            inQB.TryDequeue(out env);
            Assert.AreEqual(messAToB.ConversationId.Seq, env.Message.ConversationId.Seq);

            inQB.TryDequeue(out env);
            Assert.AreEqual(messAToBAgain.ConversationId.Seq, env.Message.ConversationId.Seq);

            inQC.TryDequeue(out env);
            Assert.AreEqual(messAToC.ConversationId.Seq, env.Message.ConversationId.Seq);

            Console.WriteLine("Here");
            tcpComA.closeCommunicator();
            tcpComB.closeCommunicator();
            tcpComC.closeCommunicator();
        }
        /// <summary>
        /// Opens a remote service that remote programs can connect (subscribe) to.
        /// </summary>
        /// <param name="service"></param>
        public RemoteService(IRemoteService service, int port)
        {
            //Starting network-layer
            this.m_InternalService = service;
            this.m_Communicator    = new TcpCommunicator <BoxedObject>("127.0.0.1", port)
            {
                DispatchMessageInEvent = true,
            };
            this.m_Communicator.Open();
            this.m_Communicator.MessageReceived += M_Communicator_MessageReceived;

            //Getting all methodinfos in the start
            this.m_ServiceMethods = service.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(mi => mi.IsSpecialName == false).ToArray();
        }
 /// <summary>
 /// Печать документа
 /// </summary>
 /// <param name="xmlData">Данные документа</param>
 public override void Print(string xmlData)
 {
     try
     {
         using (_communicator = CreateCommunicator())
         {
             _communicator.Open();
             base.Print(xmlData);
         }
     }
     finally
     {
         _communicator = null;
     }
 }
예제 #6
0
        static void Main(string[] args)
        {
            GetInput();
            var currentConfig = ClientConfiguration.GetCurrentConfiguration();
            FromServerListProvider       provider           = FromServerListProvider.Get();
            TcpCommunicator              communicator       = new TcpCommunicator(currentConfig, provider);
            IFileDroppedHandler          handler            = new FileDroppedHandler(communicator, new FileDroppedFilter(provider));
            IDropBoxServerMessageHandler fileListerner      = new DropBoxServerMessageHandler(currentConfig, communicator);
            DroppedFileWatcher           droppedFileWatcher = new DroppedFileWatcher(currentConfig.GetHomeDirectory(), "*");

            droppedFileWatcher.StartWatching();
            droppedFileWatcher.DirectoryDiff.Subscribe(async x => await handler.Handle(x.FilePath));
            Task.Factory.StartNew(() => fileListerner.InitAsync());
            Task.Factory.StartNew(() => fileListerner.Start());
            Console.ReadKey();
        }
예제 #7
0
        public void TcpComTest()
        {
            //Create the communicators
            //Create 4 queue for both systems
            EnvelopeQueue inQ1  = new EnvelopeQueue();
            EnvelopeQueue outQ1 = new EnvelopeQueue();

            EnvelopeQueue inQ2  = new EnvelopeQueue();
            EnvelopeQueue outQ2 = new EnvelopeQueue();

            TcpCommunicator tcpCom1 = new TcpCommunicator(inQ1, outQ1, new IPEndPoint(IPAddress.Loopback, 2205));
            TcpCommunicator tcpCom2 = new TcpCommunicator(inQ2, outQ2, new IPEndPoint(IPAddress.Loopback, 2206));

            //start communicator threads.
            tcpCom1.startThreads();
            tcpCom2.startThreads();

            //Create a message to send.
            AssignIdMessage mess = new AssignIdMessage(5, new byte[] { 0x1, 0x3 }, new byte[] { 0x1, 0x2 }, new Identifier(1, 1), new Identifier(1, 1));

            //Try to send a message between them
            Envelope env = new Envelope(mess, tcpCom1.getListenerEndPoint(), tcpCom2.getListenerEndPoint(), true);

            outQ1.Enqueue(env);

            //Wait for the message.
            Thread.Sleep(4000);

            //Make sure we received something.
            Assert.IsTrue(!inQ2.IsEmpty);


            //Check the message.
            Envelope tmpEnv;

            inQ2.TryDequeue(out tmpEnv);

            Assert.AreEqual(mess.getId(), ((AssignIdMessage)tmpEnv.Message).getId());

            tcpCom1.closeCommunicator();
            tcpCom2.closeCommunicator();
        }
 public DropBoxServerMessageHandler(ClientConfiguration _config, TcpCommunicator _communicator)
 {
     config       = _config;
     communicator = _communicator;
 }
 /// <summary>
 /// コンストラクタ
 /// </summary>
 /// <param name="iTcpCommunicator">切断されるTcpCommunicatorを指定します。</param>
 public TcpCommunicatorDisconnectedEventArgs(TcpCommunicator iTcpCommunicator)
 {
     this.tcpCommunicator = iTcpCommunicator;
 }
예제 #10
0
        private static void HandleClientComm(object client)
        {
            TcpClient tcpClient = (TcpClient)client;
            TcpCommunicator <Message> tcpCommunicator = new TcpCommunicator <Message>(tcpClient);

            while (tcpClient.Connected)
            {
                Message message;
                try
                {
                    message = tcpCommunicator.receive();
                    Console.WriteLine("Message reçu");
                }
                catch (CommunicatorException ex)
                {
                    Console.WriteLine(ex.Message);
                    break;
                }

                Message response = null;
                switch (message.Type)
                {
                case Updater.Message.MessageType.GetFile:
                    Console.WriteLine("Demande de fichier");
                    response      = new Message();
                    response.Type = Message.MessageType.File;
                    if (File.Exists(@"Data\" + message.Data))
                    {
                        response.BinaryData = File.ReadAllBytes(@"Data\" + message.Data);
                    }
                    break;

                case Updater.Message.MessageType.GetManifest:
                    Console.WriteLine("Demande de manifest");
                    response            = new Message();
                    response.Type       = Message.MessageType.Manifest;
                    response.BinaryData = File.ReadAllBytes(ConfigurationManager.AppSettings["manifest"]);
                    break;

                case Updater.Message.MessageType.End:
                    Console.WriteLine("Demande de fin de connexion");
                    tcpClient.Close();
                    break;

                default:
                    Console.WriteLine("Type de message inconnu");
                    break;
                }

                if (response != null)
                {
                    try
                    {
                        Console.WriteLine("Envoi de la réponse");
                        tcpCommunicator.send(response);
                    }
                    catch (CommunicatorException ex)
                    {
                        Console.WriteLine(ex.Message);
                        break;
                    }
                }
            }
        }
예제 #11
0
        public void Update()
        {
            this.UpdateState = State.CONNECTING;

            //Connexion au serveur
            TcpClient  client         = new TcpClient();
            IPEndPoint serverEndPoint = new IPEndPoint(Dns.GetHostEntry("etaverne.ddns.net").AddressList[0], 5555);

            try
            {
                client.Connect(serverEndPoint);
            }
            catch (Exception ex)
            {
                this.UpdateState = State.CONNECTION_ERROR;
                return;
            }

            TcpCommunicator <Message> tcpCommunicator = new TcpCommunicator <Message>(client);

            //Récupèration des information de mise à jour
            this.UpdateState = State.MANIFEST;
            Message message = new Message();

            message.Type = Message.MessageType.GetManifest;
            Message response;

            try
            {
                tcpCommunicator.send(message);
                response = tcpCommunicator.receive();
            }
            catch (CommunicatorException ex)
            {
                this.UpdateState = State.CONNECTION_ERROR;
                client.Close();
                return;
            }

            //Si le serveur a bien renvoyé le manifest
            if (!response.Type.Equals(Message.MessageType.Manifest))
            {
                this.UpdateState = State.CONNECTION_ERROR;
                client.Close();
                return;
            }

            //On charge les manifest
            XmlDocument manifest    = new XmlDocument();
            XmlDocument newManifest = new XmlDocument();

            MemoryStream ms = new MemoryStream(response.BinaryData);

            newManifest.Load(ms);
            ms = new MemoryStream(File.ReadAllBytes(ConfigurationManager.AppSettings["manifest"]));
            manifest.Load(ms);

            string currentVersion = manifest.SelectSingleNode("version").Attributes["id"].InnerText;
            string remoteVersion  = newManifest.SelectSingleNode("version").Attributes["id"].InnerText;

            //Si la version du serveur est différente de la version locale, on met à jour
            if (!currentVersion.Equals(remoteVersion))
            {
                this.UpdateState = State.GET_FILES;

                //Création d'un dossier temporaire pour stocker les nouveaux fichiers
                if (Directory.Exists(@"Temp"))
                {
                    DirectoryInfo directoryInfo = new DirectoryInfo(@"Temp");
                    foreach (FileInfo file in directoryInfo.GetFiles())
                    {
                        file.Delete();
                    }
                    foreach (DirectoryInfo dir in directoryInfo.GetDirectories())
                    {
                        dir.Delete(true);
                    }
                    Directory.Delete(@"Temp", true);
                }
                Directory.CreateDirectory(@"Temp");

                XmlNodeList currentFiles = manifest.SelectNodes("//fichier");
                XmlNodeList remoteFiles  = newManifest.SelectNodes("//fichier");

                //Liste des fichiers à mettre à jour
                List <string> filesToUpdate = new List <string>();

                //Pour chaque fichier dans le nouveau manifest
                foreach (XmlNode file in remoteFiles)
                {
                    bool   isOkay  = false;
                    string path    = file.SelectSingleNode("path").InnerText;
                    string version = file.SelectSingleNode("version").InnerText;

                    //On vérifie dans le manifest si le fichier existe et si sa version correspond
                    foreach (XmlNode currentFile in currentFiles)
                    {
                        string currentPath        = currentFile.SelectSingleNode("path").InnerText;
                        string currentFileVersion = currentFile.SelectSingleNode("version").InnerText;

                        if (currentPath.Equals(path))
                        {
                            isOkay = currentFileVersion.Equals(version);
                            break;
                        }
                    }

                    //Si il le faut, on met le fichier dans la liste des fichiers à mettre à jour
                    if (!isOkay)
                    {
                        filesToUpdate.Add(path);
                    }
                }

                //On récupère les fichiers non à jour
                int i = 0;
                foreach (string path in filesToUpdate)
                {
                    Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                                                                                     this.pgbarLoader.Value = i * 100 / filesToUpdate.Count));
                    i++;

                    //On créée la demande de fichier
                    message      = new Message();
                    message.Type = Message.MessageType.GetFile;
                    message.Data = path;
                    response     = null;
                    try
                    {
                        tcpCommunicator.send(message);
                        response = tcpCommunicator.receive();
                    }
                    catch (CommunicatorException ex)
                    {
                        this.UpdateState = State.CONNECTION_ERROR;
                        client.Close();
                        return;
                    }

                    //On vérifie le contenu de la réponse
                    if (!response.Type.Equals(Message.MessageType.File) || response.BinaryData == null)
                    {
                        continue;
                    }

                    //Création des répertoires
                    if (!Directory.Exists(@"Temp\" + path))
                    {
                        Directory.CreateDirectory(@"Temp\" + path);
                        Directory.Delete(@"Temp\" + path);
                    }

                    //Écriture du fichier
                    using (FileStream fs = new FileStream(@"Temp\" + path, FileMode.Create, FileAccess.Write))
                    {
                        fs.Write(response.BinaryData, 0, response.BinaryData.Length);
                    }
                }

                //On copie les nouveaux fichiers dans le répertoire de l'application
                this.UpdateState = State.UPDATE;
                int length = Directory.GetFiles(@"Temp\", "*.*", SearchOption.AllDirectories).Length;
                i = 0;
                foreach (string dirPath in Directory.GetDirectories(@"Temp\", "*", SearchOption.AllDirectories))
                {
                    Directory.CreateDirectory(dirPath.Replace(@"Temp\", @""));
                }
                foreach (string newPath in Directory.GetFiles(@"Temp\", "*.*", SearchOption.AllDirectories))
                {
                    Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                                                                                     this.pgbarLoader.Value = i++ *100 / length));
                    File.Copy(newPath, newPath.Replace(@"Temp\", @""), true);
                }

                //On supprime les fichiers qui n'existent plus dans la nouvelle version
                foreach (XmlNode file in currentFiles)
                {
                    bool   exist = false;
                    string path  = file.SelectSingleNode("path").InnerText;

                    foreach (XmlNode remoteFile in remoteFiles)
                    {
                        string remotePath = remoteFile.SelectSingleNode("path").InnerText;
                        if (remotePath.Equals(path))
                        {
                            exist = true;
                            break;
                        }
                    }

                    if (!exist)
                    {
                        File.Delete(@"" + path);
                    }
                }
            }

            //On enregistre le nouveau manifest
            this.UpdateState = State.END;
            newManifest.PreserveWhitespace = true;
            newManifest.Save(ConfigurationManager.AppSettings["manifest"]);

            //On supprime le dossier temporaire
            if (Directory.Exists(@"Temp"))
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(@"Temp");
                foreach (FileInfo file in directoryInfo.GetFiles())
                {
                    file.Delete();
                }
                foreach (DirectoryInfo dir in directoryInfo.GetDirectories())
                {
                    dir.Delete(true);
                }
                Directory.Delete(@"Temp", true);
            }

            message      = new Message();
            message.Type = Message.MessageType.End;
            try
            {
                tcpCommunicator.send(message);
            }
            catch (CommunicatorException)
            {
            }
            client.Close();
            this.UpdateState = State.READY;
        }
 /// <summary>
 /// Запрос статуса принтера
 /// </summary>
 /// <param name="communicator">Коммуникатор</param>
 protected abstract PrinterStatusFlags OnQueryPrinterStatus(TcpCommunicator communicator);
 public FileDroppedHandler(TcpCommunicator _tcpCommunicator, IFileDroppedFilter _filter)
 {
     tcpCommunicator = _tcpCommunicator;
     filter          = _filter;
 }
예제 #14
0
        public void UdpAndTcpTest()
        {
            //Create 4 queue for both systems
            EnvelopeQueue inQ1A  = new EnvelopeQueue();
            EnvelopeQueue outQ1A = new EnvelopeQueue();
            EnvelopeQueue inQ2A  = new EnvelopeQueue();
            EnvelopeQueue outQ2A = new EnvelopeQueue();

            //Create the communicators
            TcpCommunicator tcpCom1 = new TcpCommunicator(inQ1A, outQ1A, new IPEndPoint(IPAddress.Loopback, 2210)); //Sender 1
            TcpCommunicator tcpCom2 = new TcpCommunicator(inQ2A, outQ2A, new IPEndPoint(IPAddress.Loopback, 2211)); //Reciever2

            //Create the communicators
            UdpCommunicator udpCom1 = new UdpCommunicator(inQ1A, outQ1A, new IPEndPoint(IPAddress.Loopback, 2212)); //Sender 1
            UdpCommunicator udpCom2 = new UdpCommunicator(inQ2A, outQ2A, new IPEndPoint(IPAddress.Loopback, 2213)); //Reciever2

            //Start communicator threads
            tcpCom1.startThreads();
            tcpCom2.startThreads();
            udpCom1.startThreads();
            udpCom2.startThreads();

            //Create the messages
            AssignIdMessage mess1 = new AssignIdMessage(1, new byte[] { 0x1, 0x3 }, new byte[] { 0x1, 0x2 }, new Identifier(1, 1), new Identifier(1, 1));
            AssignIdMessage mess2 = new AssignIdMessage(2, new byte[] { 0x1, 0x3 }, new byte[] { 0x1, 0x2 }, new Identifier(1, 1), new Identifier(1, 1));
            AssignIdMessage mess3 = new AssignIdMessage(3, new byte[] { 0x1, 0x3 }, new byte[] { 0x1, 0x2 }, new Identifier(1, 1), new Identifier(1, 1));
            AssignIdMessage mess4 = new AssignIdMessage(4, new byte[] { 0x1, 0x3 }, new byte[] { 0x1, 0x2 }, new Identifier(1, 1), new Identifier(1, 1));

            //Make the Envelopes
            Envelope env1 = new Envelope(mess1, udpCom1.GetEndPoint(), udpCom2.GetEndPoint(), false);
            Envelope env2 = new Envelope(mess2, udpCom1.GetEndPoint(), udpCom2.GetEndPoint(), false);
            Envelope env3 = new Envelope(mess3, tcpCom1.getListenerEndPoint(), tcpCom2.getListenerEndPoint(), true);
            Envelope env4 = new Envelope(mess4, tcpCom1.getListenerEndPoint(), tcpCom2.getListenerEndPoint(), true);


            //Put in sending Q.
            outQ1A.Enqueue(env1);
            outQ1A.Enqueue(env3);
            outQ1A.Enqueue(env2);
            outQ1A.Enqueue(env4);

            Thread.Sleep(3000); //Wait for messages to send.

            //Pull out messages
            Envelope tmpEnv1;
            Envelope tmpEnv2;
            Envelope tmpEnv3;
            Envelope tmpEnv4;

            //Is there something in the Q?
            Assert.IsTrue(!inQ2A.IsEmpty);

            inQ2A.TryDequeue(out tmpEnv1);
            inQ2A.TryDequeue(out tmpEnv2);
            inQ2A.TryDequeue(out tmpEnv3);
            inQ2A.TryDequeue(out tmpEnv4);

            Console.WriteLine(((AssignIdMessage)tmpEnv1.Message).getId());
            Assert.IsTrue(1 == ((AssignIdMessage)tmpEnv1.Message).getId() | 2 == ((AssignIdMessage)tmpEnv1.Message).getId() | 3 == ((AssignIdMessage)tmpEnv1.Message).getId() | 4 == ((AssignIdMessage)tmpEnv1.Message).getId());
            Assert.IsTrue(1 == ((AssignIdMessage)tmpEnv2.Message).getId() | 2 == ((AssignIdMessage)tmpEnv2.Message).getId() | 3 == ((AssignIdMessage)tmpEnv2.Message).getId() | 4 == ((AssignIdMessage)tmpEnv2.Message).getId());
            Assert.IsTrue(1 == ((AssignIdMessage)tmpEnv3.Message).getId() | 2 == ((AssignIdMessage)tmpEnv3.Message).getId() | 3 == ((AssignIdMessage)tmpEnv3.Message).getId() | 4 == ((AssignIdMessage)tmpEnv3.Message).getId());
            Assert.IsTrue(1 == ((AssignIdMessage)tmpEnv4.Message).getId() | 2 == ((AssignIdMessage)tmpEnv4.Message).getId() | 3 == ((AssignIdMessage)tmpEnv4.Message).getId() | 4 == ((AssignIdMessage)tmpEnv4.Message).getId());

            tcpCom1.closeCommunicator();
            tcpCom2.closeCommunicator();
            udpCom1.closeCommunicator();
            udpCom2.closeCommunicator();
        }