Ejemplo n.º 1
0
        public void Start()
        {
            IPEndPoint ep = new IPEndPoint(IPAddress.Any, Port);

            listener = new TcpListener(ep);
            listener.Start();
            Task task = new Task(() => {
                while (true)
                {
                    try
                    {
                        TcpClient client = listener.AcceptTcpClient();
                        logger.Log(DateTime.Now.ToString() + " client connected", MessageTypeEnum.INFO);



                        ch.HandleClient(client, clients);

                        m_mutex.WaitOne();
                        clients.Add(client);
                        m_mutex.ReleaseMutex();
                    }
                    catch (SocketException)
                    {
                        logger.Log(DateTime.Now.ToString() + " Socket Exception ", MessageTypeEnum.FAIL);
                    }
                }
            });

            task.Start();
        }
Ejemplo n.º 2
0
        /// <summary>
        /// create handler on specific Folder - and add it to CommandRecived event
        /// </summary>
        /// <param name="path">path to Folder</param>
        private void CreateHandler(string path)
        {
            m_logging.Log("Start handle Dir: " + path, MessageTypeEnum.INFO);
            IDirectoryHandler d_handle = new DirectoyHandler(m_logging, c_controller, path);

            CommandRecieved         += d_handle.OnCommandRecieved;
            d_handle.DirectoryClose += CloseDirectory;
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Creates handler for a given directory path
        /// </summary>
        /// <param name="directory"></param>
        private void CreateHandler(string directory)
        {
            IDirectoryHandler handler = new DirectoyHandler(m_controller, m_logger);

            handler.StartHandleDirectory(directory);
            handler.DirectoryClose += onDirectoryError;
            m_logger.Log(DateTime.Now.ToString() + " deployed handler in directory " + directory, MessageTypeEnum.INFO);
            CommandRecieved += handler.OnCommandRecieved;
        }
Ejemplo n.º 4
0
        /// <summary>
        /// when stop the service, send clode command to all handlers
        /// </summary>
        protected override void OnStop()
        {
            m_logging.Log("StartCloseService", MessageTypeEnum.INFO);

            CommandRecievedEventArgs e = new CommandRecievedEventArgs((int)CommandStateEnum.CLOSE, null, "*");

            server.SendCommand(e);

            m_logging.Log("Service Stopped", MessageTypeEnum.INFO);
            EventLog.DeleteEventSource(eventSourceName);
            EventLog.Delete(logName);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="controller"> Image controller</param>
        /// <param name="logger">Image logger</param>
        public ImageServer(IImageController controller, ILoggingModel logger)
        {
            c_controller = controller;
            m_logging    = logger;
            //gets all paths of directory that needed to be handeled
            string[]      dir = AppSettingValue.Handlers.Split(';');
            StringBuilder sb  = new StringBuilder();

            foreach (string path in dir)
            {
                if (Directory.Exists(path))
                {
                    CreateHandler(path);
                    sb.Append(path).Append(';');
                }
                else
                {
                    m_logging.Log(path + " Directory dosen't found - can't handler this", MessageTypeEnum.FAIL);
                }
            }
            if (sb.Length != 0)
            {
                sb.Length--;
            }
            AppSettingValue.Handlers = sb.ToString();
        }
Ejemplo n.º 6
0
        /// <summary>
        /// The Event that will be activated upon new Command
        /// </summary>
        /// <param name="sender">is the class that call this method</param>
        /// <param name="e">save all the arguments to the event </param>
        public void OnCommandRecieved(object sender, CommandRecievedEventArgs e)
        {
            //check if the command should execute on this Directory ("*" - for all directories)
            //remember - Close has no execute command
            if (e.RequestDirPath == dirPath || e.RequestDirPath == "*")
            {
                if (e.CommandID == (int)CommandStateEnum.CLOSE) //if Command is Close
                {
                    DirectoryCloseEventArgs e1 = new DirectoryCloseEventArgs(dirPath, "Stop handle Dir: " + dirPath);
                    StopHandleDirectory();
                    DirectoryClose?.Invoke(this, e1);
                }
                else
                {//use the controller to execute
                    //for new File command taks the args[0].
                    string msg = c_imageController.ExecuteCommand(e.CommandID, e.Args, out bool result, out MessageTypeEnum type);

                    //log write the result msg, with the returning type
                    m_loggingModel.Log(msg, type);
                }
            }
        }
Ejemplo n.º 7
0
 /// <summary>
 /// this is called as an initialization when starting to handle
 /// a directory
 /// </summary>
 /// <param name="dirPath"></param>
 public void StartHandleDirectory(string dirPath)
 {
     m_path = dirPath;
     m_logging.Log(DateTime.Now.ToString() + " started handeling directory at path" + m_path, MessageTypeEnum.INFO);
     string[] filters = { "*.jpg", "*.png", "*.gif", "*.bmp" };
     foreach (string filter in filters)
     {
         try
         {
             FileSystemWatcher watcher = new FileSystemWatcher(m_path, filter);
             watcher.Created += new FileSystemEventHandler(OnCreated);
             watcher.Error   += new ErrorEventHandler(OnFileWatcherError);
             watchers.Add(watcher);
             watcher.EnableRaisingEvents = true;
         }
         catch (Exception e)
         {
             m_logging.Log(e.ToString(), MessageTypeEnum.FAIL);
         }
     }
 }
Ejemplo n.º 8
0
        public void HandleClient(TcpClient client, List <TcpClient> clients)
        {
            Task task = new Task(() => {
                bool success;
                NetworkStream stream = client.GetStream();
                BinaryReader reader  = new BinaryReader(stream, Encoding.UTF8, true);
                BinaryWriter writer  = new BinaryWriter(stream, Encoding.UTF8, true);
                while (true)
                {
                    try
                    {
                        string commandLine = reader.ReadString();
                        m_log.Log(commandLine, MessageTypeEnum.FAIL);

                        CommandRecievedEventArgs cmdArgs = CommandRecievedEventArgs.FromJSON(commandLine.ToString());
                        if (cmdArgs.CommandID == (int)CommandEnum.CloseClientCommand)
                        {
                            // if the client wants to disconnect
                            clients.Remove(client);
                            client.Close();
                        }
                        // execute the command
                        if (cmdArgs.CommandID == (int)CommandEnum.StartImageTransfer)
                        {
                            m_log.Log("entered", MessageTypeEnum.INFO);
                            string name  = cmdArgs.Args[0];
                            string image = "";
                            clients.Remove(client);

                            while (true)
                            {
                                string input = reader.ReadString();
                                m_log.Log(input, MessageTypeEnum.FAIL);

                                try
                                {
                                    CommandRecievedEventArgs finishTransfer = CommandRecievedEventArgs.FromJSON(input.ToString());
                                    if (finishTransfer.CommandID == (int)CommandEnum.FinishImageTransfer)
                                    {
                                        ExecuteCommand(finishTransfer.CommandID, new string[] { image, name }, out success);
                                        break;
                                    }
                                }
                                catch (Exception)
                                {
                                    image += input;
                                }
                            }
                            continue;
                        }
                        string cmdOut = ExecuteCommand(cmdArgs.CommandID, cmdArgs.Args, out success);

                        // write output of command to client
                        writer.Write(cmdOut);
                    }
                    catch (JsonException)
                    {
                        m_log.Log(DateTime.Now.ToString() + " Caught JSON Exception in client", MessageTypeEnum.WARNING);
                        writer.Close();
                        reader.Close();
                        return;
                    }
                    catch (Exception)
                    {
                        m_log.Log(DateTime.Now.ToString() + " I/O Exception Caught in client", MessageTypeEnum.WARNING);
                        writer.Close();
                        reader.Close();
                        return;
                    }
                }
            });

            task.Start();
        }
Ejemplo n.º 9
0
        public void Start()
        {
            IPEndPoint ep = new IPEndPoint(IPAddress.Any, Port);

            listener = new TcpListener(ep);
            listener.Start();
            Task task = new Task(() => {
                while (true)
                {
                    try
                    {
                        TcpClient client = listener.AcceptTcpClient();
                        logger.Log("Image broadcaster connected", MessageTypeEnum.INFO);
                        NetworkStream stream = client.GetStream();
                        BinaryReader reader  = new BinaryReader(stream);
                        while (true)
                        {
                            // Handle client
                            byte[] rcvLenBytes = new byte[4];
                            reader.Read(rcvLenBytes, 0, 4);
                            int rcvLen      = System.BitConverter.ToInt32(rcvLenBytes, 0);
                            byte[] rcvBytes = new byte[rcvLen];
                            reader.Read(rcvBytes, 0, rcvLen);
                            String rcv = System.Text.Encoding.ASCII.GetString(rcvBytes);

                            CommandRecievedEventArgs cmdArgs = CommandRecievedEventArgs.FromJSON(rcv);
                            if (cmdArgs.CommandID == (int)CommandEnum.StartImageTransfer)
                            {
                                string name = cmdArgs.Args[0];

                                // read image and save it
                                byte[] inputLenBytes = new byte[4];
                                reader.Read(inputLenBytes, 0, 4);
                                int inputLen = System.BitConverter.ToInt32(inputLenBytes, 0);
                                // loop to recieve all packets
                                // the amount of bytes is too big to fit in one packet
                                // so the image spreads out across multiple ones
                                byte[] inputBytes = new byte[inputLen];
                                int i             = 0;
                                do
                                {
                                    byte[] rbytes = new byte[inputLen - i];
                                    int numRead   = reader.Read(rbytes, 0, inputLen - i);
                                    for (int j = i; j < i + numRead; j++)
                                    {
                                        inputBytes[j] = rbytes[j - i];
                                    }
                                    i += numRead;
                                }while (i != inputLen);
                                // save image
                                System.IO.File.WriteAllBytes(Path.Combine(serv.pathList[0], name), inputBytes);

                                reader.Read(inputLenBytes, 0, 4);
                                inputLen   = System.BitConverter.ToInt32(inputLenBytes, 0);
                                inputBytes = new byte[inputLen];
                                reader.Read(inputBytes, 0, inputLen);
                                String input = System.Text.Encoding.ASCII.GetString(inputBytes);
                                // file transfer finished
                                CommandRecievedEventArgs finishTransfer = CommandRecievedEventArgs.FromJSON(input.ToString());
                                if (finishTransfer.CommandID == (int)CommandEnum.FinishImageTransfer)
                                {
                                    continue;
                                }
                            }
                        }
                    }
                    catch (SocketException)
                    {
                        logger.Log(DateTime.Now.ToString() + " Socket Exception ", MessageTypeEnum.FAIL);
                    }
                    catch (Exception e)
                    {
                        logger.Log("Exception in Receiver" + e.ToString(), MessageTypeEnum.FAIL);
                    }
                }
            });

            task.Start();
        }