Example #1
0
        /// <summary>
        /// In some scenarios, a StreamReader will be blocked on read() when trying to dispose it.
        /// On OS X under mono, read() will block any close() syscalls on the file descriptor for the stream.
        /// Therefore, we write a byte to unblock the read() and allow close() to succeed.
        /// Callers to this function should document why read() might be blocked.
        /// </summary>
        /// <param name="reader">The StreamReader to forcibly dispose</param>
        protected static void ForceDisposeStreamReader(StreamReader reader)
        {
            try
            {
                reader?.BaseStream.WriteByte(0);
            }
            catch
            {
            }

            reader?.Dispose();
        }
        /// <summary>
        /// Observe String-Line from file like tail -f.
        /// </summary>
        /// <param name="encoding">If null, use Encoding.UTF8</param>
        public static IObservable<string> FromFileTail(string filePath, bool readFromFirstLine = false, Encoding encoding = null)
        {
            return Observable.Defer(() =>
            {
                encoding = encoding ?? Encoding.UTF8;

                var subject = new Subject<string>();

                var fi = new System.IO.FileInfo(filePath);

                var stream = fi.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                var streamReader = new StreamReader(stream, encoding);

                try
                {
                    var firstSource = new List<string>();
                    if (readFromFirstLine)
                    {
                        while (!streamReader.EndOfStream)
                        {
                            firstSource.Add(streamReader.ReadLine());
                        }
                    }
                    else
                    {
                        stream.Seek(fi.Length, SeekOrigin.Current);
                    }

                    var readingLock = new object();
                    var fsw = new FileSystemWatcher(fi.DirectoryName, fi.Name);
                    fsw.NotifyFilter = NotifyFilters.Size;
                    fsw.Changed += (sender, e) =>
                    {
                        try
                        {
                            lock (readingLock)
                            {
                                string s;
                                while ((s = streamReader.ReadLine()) != null)
                                {
                                    if (s != "")
                                    {
                                        subject.OnNext(s);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            subject.OnError(ex);
                        }
                    };
                    fsw.EnableRaisingEvents = true;

                    return firstSource.ToObservable().Concat(subject).Finally(() =>
                    {
                        fsw.EnableRaisingEvents = false;
                        fsw.Dispose();
                        streamReader.Dispose();
                        stream.Dispose();
                    });
                }
                catch
                {
                    streamReader?.Dispose();
                    stream?.Dispose();
                    throw;
                }
            });
        }
Example #3
0
        public static async Task HandleClientAsync(TcpClient client, CancellationToken cancel)
        {
            await Task.Yield();
            StreamReader sr = null;
            StreamWriter sw = null;
            try
            {
                var stream = client.GetStream();
                sr = new StreamReader(stream, Encoding.UTF8);
                sw = new StreamWriter(stream, Encoding.UTF8);
                while (!cancel.IsCancellationRequested && client.Connected)
                {
                    var inputDesktop = new Desktop();
                    inputDesktop.OpenInput();
                    if (!inputDesktop.DesktopName.Equals(LastDesktop))
                    {
                        var switched = inputDesktop.Show();

                        if (switched)
                        {
                            var setCurrent = Desktop.SetCurrent(inputDesktop);
                            if (setCurrent)
                            {
                                Console.WriteLine(
                                    $"Desktop switched from {LastDesktop} to {inputDesktop.DesktopName}");
                                LastDesktop = inputDesktop.DesktopName;
                                lastDesktopInput = inputDesktop;
                            }
                            else
                            {
                                lastDesktopInput.Close();
                            }
                        }
                    }
                    else
                    {
                        inputDesktop.Close();
                    }
                    var endpoint = await sr.ReadLineAsync();
                    if (string.IsNullOrEmpty(endpoint))
                    {
                        break;
                    }
                    string[] endpointArgs = { };
                    if (endpoint.Contains("|"))
                    {
                        var splitPoint = endpoint.Split('|');
                        endpointArgs = splitPoint[1].Split(',');
                        endpoint = splitPoint[0];
                    }
                    string response = null;
                    switch (endpoint)
                    {
                        case "fullframe":
                            var frameData = SendFullFrame();
                            response = frameData.Length == 0 ? "n" : Convert.ToBase64String(frameData);
                            break;
                        case "cleanframe":
                            var cleanFrameData = SendCleanFrame();
                            response = cleanFrameData.Length == 0 ? "n" : Convert.ToBase64String(cleanFrameData);
                            break;
                        case "ctrlaltdel":
                            HandleCtrlAltDel();
                            break;
                        case "rightdown":
                            HandleRightDown();
                            break;
                        case "rightup":
                            HandleRightUp();
                            break;
                        case "mousemove":
                            int x = Convert.ToInt16(endpointArgs[0], CultureInfo.InvariantCulture);
                            int y = Convert.ToInt16(endpointArgs[1], CultureInfo.InvariantCulture);
                            MoveMouse(x, y);
                            break;
                        case "mousedown":
                            HandleMouseDown();
                            break;
                        case "mousescroll":
                            HandleMouseScroll(endpointArgs[0]);
                            break;
                        case "mouseup":
                            HandleMouseUp();
                            break;
                        case "leftclick":
                            break;
                        case "rightclick":
                            HandleRightClick();
                            break;
                        case "keydown":
                            KeyDown(endpointArgs);
                            break;
                        case "keyup":
                            Keyup(endpointArgs);
                            break;
                    }
                    if (string.IsNullOrEmpty(response))
                    {
                        break;
                    }
                    await sw.WriteLineAsync(response);
                    await sw.FlushAsync();
                    await Task.Yield();
                }
            }
            catch (Exception aex)
            {
                var ex = aex.GetBaseException();
                Console.WriteLine("Client error: " + ex.Message);
            }
            finally
            {
                sr?.Dispose();

                sw?.Dispose();
            }
        }