예제 #1
0
        private void Encoder_Data_Available(object sender, VideoEventArgs e)
        {
            frame++;

            framebytes = e.payload.outbytes;

            lastframe       = e.payload.uncompressedFrame;
            lastframestride = e.payload.stride;
            lastframeheight = e.payload.height;
            lastframewidth  = e.payload.width;


            if (isConnected)
            {
                VideoStream.Write(e.payload.result, 0, e.payload.outbytes);
                VideoStream.Flush();
                VideoStream.WaitForPipeDrain();

                video.ReturnWork(e.payload);
            }
            if (enableWriteToFile && binaryVideoWriter != null)
            {
                binaryVideoWriter.Write(e.payload.result, 0, e.payload.outbytes);
                binaryVideoWriter.Flush();
            }
        }
예제 #2
0
        public AnonymousPipes(String pipeName, String clientPath, String cmdLineArgs, CallBack callback, DisconnectEvent disconnectEvent)
        {
            String args;

            this.clientPath      = clientPath;
            this.callback        = callback;
            this.disconnectEvent = disconnectEvent;
            this.name            = pipeName;
            this.running         = true;

            serverMode = true;

            args = StartPipeServer() + " " + cmdLineArgs;

            try
            {
                pipeClient = new Process();
                pipeClient.StartInfo.FileName        = clientPath;
                pipeClient.StartInfo.Arguments       = args;
                pipeClient.StartInfo.UseShellExecute = false;
                pipeClient.Start();
            } catch (Exception ex)
            {
                ermsg   = ex.Message;
                running = false;
                return;
            }

            outGoingServerPipe.DisposeLocalCopyOfClientHandle();
            inComingServerPipe.DisposeLocalCopyOfClientHandle();

            ssw           = new StreamWriter(outGoingServerPipe);
            ssw.AutoFlush = true;
            ssw.WriteLine("SYNC");

            outGoingServerPipe.WaitForPipeDrain();

            new Thread(delegate()
            {
                using (StreamReader isr = new StreamReader(inComingServerPipe))
                {
                    String tmp;
                    while (running && inComingServerPipe.IsConnected)
                    {
                        tmp = isr.ReadLine();
                        if (tmp != null)
                        {
                            callback(tmp);
                        }
                    }
                }

                running = false;
                disconnectEvent();
            }).Start();
        }
예제 #3
0
        static void Main(string[] args)
        {
            Process pipeClient1 = new Process();

            pipeClient1.StartInfo.FileName = @"AnonymousPipeClient.exe";

            //AnonymousPipeServerStream is an one-way pipe. in other words it's only support PipeDirection.In or PipeDirection.Out.
            //in this program, we use PipeDirection.Out for send data to clients.
            using (AnonymousPipeServerStream pipeServer =
                       new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
            {
                //send the client handle that from AnonymousPipeServerStream to client
                pipeClient1.StartInfo.Arguments       = pipeServer.GetClientHandleAsString();
                pipeClient1.StartInfo.UseShellExecute = false;
                pipeClient1.Start();

                //closes the local copy of the AnonymousPipeClientStream object's handle
                //this method must be call after the client handle has been passed to the client
                //if this method isn't called, then the AnonymousPipeServerStream will not receive notice when client dispose of it's PipeStream object
                pipeServer.DisposeLocalCopyOfClientHandle();

                try
                {
                    using (StreamWriter sw = new StreamWriter(pipeServer))
                    {
                        //automatic flush
                        sw.AutoFlush = true;

                        sw.WriteLine("SYNC");
                        //it'll block util the other end of pipe has been read all send bytes
                        pipeServer.WaitForPipeDrain();

                        String temp = null;
                        while (true)
                        {
                            temp = Console.ReadLine();
                            //send message to pipeclient from console
                            sw.WriteLine(temp);
                            //it'll block util the other end of pipe has been read all send bytes
                            pipeServer.WaitForPipeDrain();
                            if (temp == "exit")
                            {
                                break;
                            }
                        }
                    }
                }
                catch (IOException e)
                {
                    Console.WriteLine("[server] exception:{0}", e.Message);
                }
            }

            pipeClient1.WaitForExit();
            pipeClient1.Close();
        }
예제 #4
0
 public void Stop()
 {
     m_Server.WaitForPipeDrain();
     m_Server.Close();
     m_Client.Close();
     m_Client.Dispose();
     m_Client = null;
     m_Server.Dispose();
     m_Server = null;
 }
예제 #5
0
 private void Audio_RecordingStopped(object sender, StoppedEventArgs e)
 {
     if (isConnected)
     {
         AudioStream.Flush();
         AudioStream.WaitForPipeDrain();
     }
     if (enableWriteToFile && binaryAudioWriter != null)
     {
         binaryAudioWriter.Flush();
         binaryAudioWriter.Close();
         binaryAudioWriter.Dispose();
     }
 }
예제 #6
0
        void run()
        {
            using (pipeServer)
            {
                StartClient(pipeServer.GetClientHandleAsString());
                pipeServer.DisposeLocalCopyOfClientHandle();

                using (sw)
                {
                    sw.AutoFlush = true;
                    sw.WriteLine("SYNC");
                    pipeServer.WaitForPipeDrain();
                    while (true)
                    {
                        try
                        {
                            Evnt.WaitOne();
                            sw.WriteLine(x);
                            sw.WriteLine(y);
                            sem.Release();
                        }
                        catch (SemaphoreFullException)
                        {
                        }
                    }
                }
            }
        }
예제 #7
0
        /// <summary>
        /// Main task thread for working with a single APSIMRunner.exe process using
        /// an anonymous pipe.
        /// </summary>
        private void PipeServerTaskThread()
        {
            // Create 2 anonymous pipes (read and write) for duplex communications
            // (each pipe is one-way)
            using (var pipeRead = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable))
                using (var pipeWrite = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
                {
                    var pipeHandles = pipeRead.GetClientHandleAsString() + " " + pipeWrite.GetClientHandleAsString();

                    // Run a APSIMRunner process passing the pipe read and write handles as arguments.
                    var runnerProcess = new ProcessUtilities.ProcessWithRedirectedOutput();
                    runnerProcess.Exited += OnExited;
                    var runnerExecutable = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "APSIMRunner.exe");
                    runnerProcess.Start(executable: runnerExecutable,
                                        arguments: pipeHandles,
                                        workingDirectory: Directory.GetCurrentDirectory(),
                                        redirectOutput: true,
                                        writeToConsole: false);

                    // Release the local handles that were created with the above GetClientHandleAsString calls
                    pipeRead.DisposeLocalCopyOfClientHandle();
                    pipeWrite.DisposeLocalCopyOfClientHandle();

                    try
                    {
                        // Get the next job to run.
                        var job = GetJobToRun();

                        while (job != null)
                        {
                            var startTime = DateTime.Now;

                            // Send the job to APSIMRunner.exe - this will run the simulation.
                            PipeUtilities.SendObjectToPipe(pipeWrite, job.JobSentToClient);

                            pipeWrite.WaitForPipeDrain();

                            // Get the output data back from APSIMRunner.exe
                            var endJob = PipeUtilities.GetObjectFromPipe(pipeRead) as JobOutput;

                            // Send the output data to storage.
                            endJob.WriteOutput(job.DataStore);

                            // Signal end of job.
                            InvokeJobCompleted(job.RunnableJob,
                                               job.JobManager,
                                               startTime,
                                               endJob.ErrorMessage);

                            // Get the next job to run.
                            job = GetJobToRun();
                        }
                    }
                    catch (Exception err)
                    {
                        AddException(err);
                    }
                }
        }
예제 #8
0
파일: Program.cs 프로젝트: dessarn/Checkout
 private static void sendToBasketApp(AnonymousPipeServerStream pipeServer, StreamWriter sw, string sendingString)
 {
     // Send a 'sync message' and wait for client to receive it.
     sw.WriteLine("SYNC");
     pipeServer.WaitForPipeDrain();
     // Send the console input to the client process.
     sw.WriteLine(sendingString);
 }
예제 #9
0
        public static void StartProcess()
        {
            Process pipeClient = new Process();

            pipeClient.StartInfo.FileName = "child.exe";

            using (AnonymousPipeServerStream pipeServer =
                       new AnonymousPipeServerStream(PipeDirection.Out,
                                                     HandleInheritability.Inheritable))
            {
                // Show that anonymous pipes do not support Message mode.
                try
                {
                    Console.WriteLine("[SERVER] Setting ReadMode to \"Message\".");
                    pipeServer.ReadMode = PipeTransmissionMode.Message;
                }
                catch (NotSupportedException e)
                {
                    Console.WriteLine("[SERVER] Exception:\n    {0}", e.Message);
                }

                Console.WriteLine("[SERVER] Current TransmissionMode: {0}.",
                                  pipeServer.TransmissionMode);

                // Pass the client process a handle to the server.
                pipeClient.StartInfo.Arguments =
                    pipeServer.GetClientHandleAsString();
                pipeClient.StartInfo.UseShellExecute = false;
                pipeClient.Start();

                pipeServer.DisposeLocalCopyOfClientHandle();

                try
                {
                    // Read user input and send that to the client process.
                    using (StreamWriter sw = new StreamWriter(pipeServer))
                    {
                        sw.AutoFlush = true;
                        // Send a 'sync message' and wait for client to receive it.
                        sw.WriteLine("SYNC");
                        pipeServer.WaitForPipeDrain();
                        // Send the console input to the client process.
                        Console.Write("[SERVER] Enter text: ");
                        sw.WriteLine(Console.ReadLine());
                    }
                }
                // Catch the IOException that is raised if the pipe is broken
                // or disconnected.
                catch (IOException e)
                {
                    Console.WriteLine("[SERVER] Error: {0}", e.Message);
                }
            }

            pipeClient.WaitForExit();
            pipeClient.Close();
            Console.WriteLine("[SERVER] Client quit. Server terminating.");
        }
예제 #10
0
    static void Main()
    {
        Process pipeClient = new Process();

        pipeClient.StartInfo.FileName = "C:/Users/martinH/Desktop/BuiltUnityGame/5cube2fish.exe";
        int counter = 0;

        using (AnonymousPipeServerStream pipeServer =
                   new AnonymousPipeServerStream(PipeDirection.Out,
                                                 HandleInheritability.Inheritable))
        {
            Console.WriteLine("[SERVER] Current TransmissionMode: {0}.",
                              pipeServer.TransmissionMode);

            // Pass the client process a handle to the server.
            pipeClient.StartInfo.Arguments =
                pipeServer.GetClientHandleAsString();
            pipeClient.StartInfo.UseShellExecute = false;
            pipeClient.Start();

            pipeServer.DisposeLocalCopyOfClientHandle();

            try
            {
                // Read user input and send that to the client process.
                using (StreamWriter sw = new StreamWriter(pipeServer))
                {
                    // sw.AutoFlush = true;
                    sw.AutoFlush = false;
                    Console.WriteLine("Before Loop");
                    while (counter < 200000)
                    {
                        //sw.AutoFlush = true;
                        // Send a 'sync message' and wait for client to receive it.
                        sw.WriteLine(counter.ToString());
                        Console.WriteLine("Writing Sample" + counter.ToString());
                        pipeServer.WaitForPipeDrain();
                        counter++;
                        // Send the console input to the client process.
                        // Console.Write("[SERVER] Enter text: ");
                        // sw.WriteLine(Console.ReadLine());
                    }
                    Console.WriteLine("Wrote 200K Samples");
                }
            }
            // Catch the IOException that is raised if the pipe is broken
            // or disconnected.
            catch (IOException e)
            {
                Console.WriteLine("[SERVER] Error: {0}", e.Message);
            }
        }

        pipeClient.WaitForExit();
        pipeClient.Close();
        Console.WriteLine("[SERVER] Client quit. Server terminating.");
    }
예제 #11
0
        public Relay(Options options)
        {
            log.Info("creating relay host");

            log.Debug("create interprocess input pipe");
            pipeIn     = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);
            pipeReader = new StreamReader(pipeIn);

            log.Debug("create interprocess output pipe");
            pipeOut    = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
            pipeWriter = new StreamWriter(pipeOut);

            log.Debug("create processor host");
            processor = new Process();
            processor.StartInfo.FileName = System.Reflection.Assembly.GetExecutingAssembly().Location;
            log.DebugFormat("StartInfo.FileName={0}", processor.StartInfo.FileName);
            processor.StartInfo.Arguments = String.Format("--pipe-in={0} --pipe-out={1} process", pipeOut.GetClientHandleAsString(), pipeIn.GetClientHandleAsString());
            log.DebugFormat("StartInfo.Arguments={0}", processor.StartInfo.Arguments);
            processor.StartInfo.UseShellExecute = false;

            log.Debug("start processor host");
            try
            {
                processor.Start();
            }
            catch (Exception ex)
            {
                log.Fatal("Exception while starting processor host.", ex);
                throw ex;
            }
            log.DebugFormat("processor host process id : {0}", processor.Id);

            log.Debug("join processes into a job so processor host dies together with relay host");
            job = new Job();
            job.AddProcess(Process.GetCurrentProcess().Id);
            job.AddProcess(processor.Id);

            log.Debug("create native messaging ports");
            portA           = new Port();
            portB           = new Port(pipeIn, pipeOut);
            portsExceptions = new List <Exception>();

            log.Debug("create stop event");
            stop = new ManualResetEvent(false);

            log.Debug("synchronize processes");
            string sync = "SYNC";

            pipeWriter.WriteLine(sync);
            pipeWriter.Flush();
            log.DebugFormat("sent {0}", sync);
            pipeOut.WaitForPipeDrain();
            sync = pipeReader.ReadLine();
            log.DebugFormat("received {0}", sync);

            log.Info("created relay host");
        }
        public void SendLog(LogMessage logMessage)
        {
            try
            {
                _pipeServerStreamWriter.WriteLine(JsonConvert.SerializeObject(logMessage));

                _logsManagerPipeServer.WaitForPipeDrain();
            }
            catch (IOException e)
            {
                Console.WriteLine("[SERVER] Error: {0}", e.Message);
            }
        }
예제 #13
0
        static void Main(string[] args)
        {
            string fileName;

            if (File.Exists("PipeClient.exe"))
            {
                fileName = "PipeClient.exe";
            }
            else
            {
                fileName = "PipeClientCpp.exe";
            }

            Process pipeClientProcess = new Process();

            pipeClientProcess.StartInfo.FileName = fileName;

            using (var pipeServer = new AnonymousPipeServerStream(
                       PipeDirection.Out, HandleInheritability.Inheritable))
            {
                Console.WriteLine("[SERVER] Current TransmissionMode: {0}.", pipeServer.TransmissionMode);

                pipeClientProcess.StartInfo.Arguments       = pipeServer.GetClientHandleAsString();
                pipeClientProcess.StartInfo.UseShellExecute = false;
                pipeClientProcess.Start();

                pipeServer.DisposeLocalCopyOfClientHandle();

                try
                {
                    using (var streamWriter = new StreamWriter(pipeServer))
                    {
                        streamWriter.AutoFlush = true;
                        streamWriter.WriteLine("SYNC");
                        pipeServer.WaitForPipeDrain();
                        Console.Write("[SERVER] Enter text: ");
                        streamWriter.WriteLine(Console.ReadLine());
                    }
                }
                catch (IOException e)
                {
                    Console.WriteLine("[SERVER] Error: {0}", e.Message);
                }
            }

            pipeClientProcess.WaitForExit();
            pipeClientProcess.Close();
            Console.WriteLine("[SERVER] Client quit. Server terminating.");

            Console.ReadKey();
        }
예제 #14
0
        public void StartPatcher()
        {
            var process = new Process
            {
                StartInfo =
                {
                    FileName         = Path.Combine(Directory.GetCurrentDirectory(), "XIVLauncher.PatchInstaller.exe"),
                    WorkingDirectory = Directory.GetCurrentDirectory()
                }
            };

            process.StartInfo.Verb = "runas";

            using (var pipeServer =
                       new AnonymousPipeServerStream(PipeDirection.InOut,
                                                     HandleInheritability.Inheritable))
            {
                Console.WriteLine("[SERVER] Current TransmissionMode: {0}.",
                                  pipeServer.TransmissionMode);

                // Pass the client process a handle to the server.
                process.StartInfo.Arguments =
                    pipeServer.GetClientHandleAsString();
                process.StartInfo.UseShellExecute = false;
                process.Start();

                pipeServer.DisposeLocalCopyOfClientHandle();

                try
                {
                    // Read user input and send that to the client process.
                    using (StreamWriter sw = new StreamWriter(pipeServer))
                    {
                        sw.AutoFlush = true;
                        // Send a 'sync message' and wait for client to receive it.
                        sw.WriteLine("SYNC");
                        pipeServer.WaitForPipeDrain();
                        // Send the console input to the client process.
                        Console.Write("[SERVER] Enter text: ");
                        sw.WriteLine(Console.ReadLine());
                    }
                }
                // Catch the IOException that is raised if the pipe is broken
                // or disconnected.
                catch (IOException e)
                {
                    Console.WriteLine("[SERVER] Error: {0}", e.Message);
                }
            }
        }
예제 #15
0
 public void Close()
 {
     if (!_disposed)
     {
         lock (this)
             if (!_disposed)
             {
                 _server.WaitForPipeDrain();
                 _server.Close();
                 _client.Close();
                 _disposed = true;
             }
     }
 }
예제 #16
0
        static void Main(string[] args)
        {
            Console.WriteLine("Kinect for Beat Saber | By Caeden117");
            Console.WriteLine("Any launch args for this application will transfer over to Beat Saber! (\"--verbose\" and \"fpfc\", for example.)");
            Console.WriteLine("Current launch args: " + string.Join(" ", args));
            Console.WriteLine("=============================");
            Console.WriteLine("Waiting for Kinect...");
            chooser = new KinectSensorChooser();
            chooser.KinectChanged += KinectUpdate;
            chooser.Start();
            Process.GetCurrentProcess().Exited += Exit;
            Console.WriteLine("Kinect active. Launching Beat Saber...");

            serverStream = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable)
            {
                ReadMode = PipeTransmissionMode.Byte
            };

            beatSaber = new Process();
            beatSaber.StartInfo.FileName        = "Beat Saber.exe"; //This NEEDS to be placed in the root Beat Saber folder
            beatSaber.StartInfo.Arguments       = $"{string.Join(" ", args)} KinectClientHandle={serverStream.GetClientHandleAsString()}";
            beatSaber.StartInfo.UseShellExecute = false;
            beatSaber.Start();

            serverStream.DisposeLocalCopyOfClientHandle();

            try
            {
                Console.WriteLine("Attempting to establish connection...");
                sw = new StreamWriter(serverStream)
                {
                    AutoFlush = true
                };
                sw.WriteLine("SYNC");
                serverStream.WaitForPipeDrain();
                Console.WriteLine("Connection established! We are good to go!");
            }
            catch (IOException e)
            {
                Console.WriteLine(e);
                Console.WriteLine("Connection has been terminated.");
            }

            beatSaber.WaitForExit();
            beatSaber.Close();
            Console.WriteLine("Beat Saber terminated. Terminating self...");
            //Console.ReadLine();
            Process.GetCurrentProcess().Close();
        }
예제 #17
0
        public static void ServerReadOnlyThrows()
        {
            using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.In))
            {
                Assert.Throws <NotSupportedException>(() => server.Write(new byte[5], 0, 5));

                Assert.Throws <NotSupportedException>(() => server.WriteByte(123));

                Assert.Throws <NotSupportedException>(() => server.Flush());

                Assert.Throws <NotSupportedException>(() => server.OutBufferSize);

                Assert.Throws <NotSupportedException>(() => server.WaitForPipeDrain());
            }
        }
예제 #18
0
        void StartProcess()
        {
            this.pipeClient = new Process();
            pipeClient.StartInfo.FileName = "pipeClient.exe";
            this.eventHandled             = new TaskCompletionSource <bool>();


            using (AnonymousPipeServerStream pipeServer = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
            {
                Console.WriteLine("[SERVER] Current TransmissionMode: {0}.", pipeServer.TransmissionMode);

                // Pass the client process a handle to the server.
                pipeClient.StartInfo.Arguments       = pipeServer.GetClientHandleAsString();
                pipeClient.StartInfo.UseShellExecute = false;
                // para el exited
                pipeClient.EnableRaisingEvents = true;
                pipeClient.Exited += new EventHandler(myProcess_Exited);
                pipeClient.Start();

                pipeServer.DisposeLocalCopyOfClientHandle();

                try
                {
                    // Read user input and send that to the client process.
                    using (StreamWriter sw = new StreamWriter(pipeServer))
                    {
                        sw.AutoFlush = true;
                        // Send a 'sync message' and wait for client to receive it.
                        sw.WriteLine("SYNC");
                        pipeServer.WaitForPipeDrain();
                        // Send the console input to the client process.
                        Console.Write("[SERVER] Enter text: ");
                        sw.WriteLine(Console.ReadLine());
                    }
                }
                // Catch the IOException that is raised if the pipe is broken
                // or disconnected.
                catch (IOException e)
                {
                    Console.WriteLine("[SERVER] Error: {0}", e.Message);
                }
            }

            pipeClient.WaitForExit();
            pipeClient.Close();
            Console.WriteLine("[SERVER] Client quit. Server terminating.");
            Console.ReadLine();
        }
예제 #19
0
        public static void Main()
        {
            Process pipeClient = new Process();

            pipeClient.StartInfo.FileName = "PipeClient.exe";

            using (var pipeServer = new AnonymousPipeServerStream(PipeDirection.Out,
                                                                  HandleInheritability.Inheritable))
            {
                try
                {
                    Console.Write("[SERVER] Setting ReadMode to \"Message\".");
                    pipeServer.ReadMode = PipeTransmissionMode.Message;
                }
                catch (NotSupportedException e)
                {
                    Console.WriteLine("[SERVER] Exception:\n  {0}", e.Message);
                }

                Console.WriteLine("[SERVER] Current TransmissionMode: {0}.", pipeServer.TransmissionMode);

                pipeClient.StartInfo.Arguments       = pipeServer.GetClientHandleAsString();
                pipeClient.StartInfo.UseShellExecute = false;
                pipeClient.Start();

                pipeServer.DisposeLocalCopyOfClientHandle();
                try
                {
                    using (var sw = new StreamWriter(pipeServer))
                    {
                        sw.AutoFlush = true;
                        sw.WriteLine("SYNC");                         // Send a 'sync message' and wait for client to receive it.
                        pipeServer.WaitForPipeDrain();
                        Console.Write("[SERVER] Enter text: ");
                        sw.WriteLine(Console.ReadLine());
                    }
                }
                catch (IOException e)                 // if the pipe is broken or disconnected.
                {
                    Console.WriteLine("[SERVER] Error: {0}", e.Message);
                }
            }

            pipeClient.WaitForExit();
            pipeClient.Close();
            Console.WriteLine("[SERVER] Client quit. Server terminating.");
        }
예제 #20
0
파일: DAQ.cs 프로젝트: jingxlim/FictiveVR
        public void StartServer()
        {
            Process pipeClient = new Process();

            pipeClient.StartInfo.FileName = "C:/Users/martinH/Desktop/BuiltUnityGame/5cube2fish.exe";
            using (AnonymousPipeServerStream pipeServer =
                       new AnonymousPipeServerStream(PipeDirection.Out,
                                                     HandleInheritability.Inheritable))
            {
                // Pass the client process a handle to the server.
                pipeClient.StartInfo.Arguments =
                    pipeServer.GetClientHandleAsString();
                pipeClient.StartInfo.UseShellExecute = false;
                pipeClient.Start();
                pipeServer.DisposeLocalCopyOfClientHandle();
                try
                {
                    // Read user input and send that to the client process.
                    using (StreamWriter sw = new StreamWriter(pipeServer))
                    {
                        sw.AutoFlush = false;
                        while (!token.IsCancellationRequested)
                        {
                            buffer_input = ringBuffer.Receive();
                            // This is all good here. Writes the correct value.
                            //     Console.WriteLine(buffer_input.Item1.ToString());
                            tail_left_voltages.Enqueue(buffer_input.Item1);
                            // Console.WriteLine(tail_left_voltages.Dequeue().ToString());
                            tail_right_voltages.Enqueue(buffer_input.Item2);
                            movement_command = GenerateTailCommand();
                            sw.WriteLine(movement_command);
                            pipeServer.WaitForPipeDrain();
                        }
                    }
                }
                // Catch the IOException that is raised if the pipe is broken
                // or disconnected.
                catch (IOException e)
                {
                    Console.WriteLine("[SERVER] Error: {0}", e.Message);
                }
            }
            pipeClient.WaitForExit();
            pipeClient.Close();
            Console.WriteLine("[SERVER] Client quit. Server terminating.");
        }
        private async Task SendPayload(string payload)
        {
            await Task.Run(() =>
            {
                try
                {
                    _streamWriter.WriteLine(payload);

                    _pipeServerStream.WaitForPipeDrain();

                    Log("Render data sent to the renderer.");
                }
                catch (Exception e)
                {
                    Log($"Error: {e.Message}");
                }
            });
        }
예제 #22
0
        private void LaunchToaster(Message bread)
        {
            using (var server = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
            {
                ProcessStartInfo psi = new ProcessStartInfo()
                {
                    RedirectStandardInput = true,
                    UseShellExecute       = false,
                    FileName = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"toasterpath")),
                };

                psi.Arguments += $" --pipe-id={server.GetClientHandleAsString()}";

                if (this.GetSettingOrDefault <bool>(GrowlerSetting.DebugLogging, false))
                {
                    psi.Arguments += " --loglevel-debug";
                }

                Process p = new Process()
                {
                    StartInfo = psi
                };

                p.Start();

                server.DisposeLocalCopyOfClientHandle();

                try
                {
                    using (var writer = new StreamWriter(server))
                    {
                        string json = JsonConvert.SerializeObject(bread);
                        writer.Write(json);
                        writer.Flush();
                    }
                    server.WaitForPipeDrain();
                }
                catch (IOException ex)
                {
                    // Growler doesn't have logging (yet?)
                    System.Windows.Forms.MessageBox.Show($"Pipe to Toaster broken, {ex}");
                }
            }
        }
예제 #23
0
        public static void Run()
        {
            using var clientProccess = new Process();
            using var outPipe        = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
            using var inPipe         = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);

            var clientHandleOut = outPipe.GetClientHandleAsString();
            var clientHandleIn  = inPipe.GetClientHandleAsString();

            var clientArgs = new System.Text.StringBuilder();

            clientArgs.Append(clientHandleOut);
            clientArgs.Append(" ");
            clientArgs.Append(clientHandleIn);
            clientArgs.Append(" ");
            clientArgs.Append(timesToRun);

            clientProccess.StartInfo.Arguments = clientArgs.ToString();
            clientProccess.StartInfo.FileName  = @"C:\Users\slima\source\Repos\sasha-limarev\fs\c#\AnonPipeClient\bin\Debug\netcoreapp3.0\AnonPipePong.exe";

            clientProccess.Start();

            outPipe.DisposeLocalCopyOfClientHandle();
            inPipe.DisposeLocalCopyOfClientHandle();

            using var serverReader = new StreamReader(inPipe);
            using var serverWriter = new StreamWriter(outPipe)
                  {
                      AutoFlush = true
                  };

            for (int i = 0; i < timesToRun; ++i)
            {
                serverWriter.WriteLine(lineToSend);

                outPipe.WaitForPipeDrain();

                var currLine = serverReader.ReadLine();

                Console.WriteLine(currLine);

                Thread.Sleep(100);
            }
        }
예제 #24
0
    public static void ServerPInvokeChecks()
    {
        // calling every API related to server and client to detect any bad PInvokes
        using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.Out))
        {
            Task clientTask = Task.Run(() => StartClient(PipeDirection.In, server.ClientSafePipeHandle));

            Assert.False(server.CanRead);
            Assert.False(server.CanSeek);
            Assert.False(server.CanTimeout);
            Assert.True(server.CanWrite);
            Assert.False(string.IsNullOrWhiteSpace(server.GetClientHandleAsString()));
            Assert.False(server.IsAsync);
            Assert.True(server.IsConnected);
            Assert.Equal(0, server.OutBufferSize);
            Assert.Equal(PipeTransmissionMode.Byte, server.ReadMode);
            Assert.NotNull(server.SafePipeHandle);
            Assert.Equal(PipeTransmissionMode.Byte, server.TransmissionMode);

            server.Write(new byte[] { 123 }, 0, 1);
            server.WriteAsync(new byte[] { 124 }, 0, 1).Wait();
            server.Flush();
            server.WaitForPipeDrain();

            clientTask.Wait();
            server.DisposeLocalCopyOfClientHandle();
        }

        using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.In))
        {
            Task clientTask = Task.Run(() => StartClient(PipeDirection.Out, server.ClientSafePipeHandle));

            Assert.Equal(4096, server.InBufferSize);
            byte[] readData = new byte[] { 0, 1 };
            Assert.Equal(1, server.Read(readData, 0, 1));
            Assert.Equal(1, server.ReadAsync(readData, 1, 1).Result);
            Assert.Equal(123, readData[0]);
            Assert.Equal(124, readData[1]);

            clientTask.Wait();
        }
    }
예제 #25
0
        static void Main(string[] args)
        {
            using (AnonymousPipeServerStream pipedServer = new AnonymousPipeServerStream(PipeDirection.Out))
            {
                Thread child = new Thread(new ParameterizedThreadStart(childThread));
                child.Start(pipedServer.GetClientHandleAsString());

                using (StreamWriter sw = new StreamWriter(pipedServer))
                {
                    var data = string.Empty;
                    sw.AutoFlush = true;
                    while (!data.Equals("quit", StringComparison.InvariantCultureIgnoreCase))
                    {
                        pipedServer.WaitForPipeDrain();
                        Console.WriteLine("SERVER : ");
                        data = Console.ReadLine();
                        sw.WriteLine(data);
                    }
                }
            }
        }
예제 #26
0
        public async Task SendAsync(Process p, string value)
        {
            using (AnonymousPipeServerStream pipeServer = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
            {
                try
                {
                    Console.WriteLine("[SERVER] Setting ReadMode to \"Message\".");
                    pipeServer.ReadMode = PipeTransmissionMode.Message;
                }
                catch (NotSupportedException e)
                {
                    Console.WriteLine("[SERVER] Exception:\n    {0}", e.Message);
                }

                Console.WriteLine("[SERVER] Current TransmissionMode: {0}.",
                                  pipeServer.TransmissionMode);

                Console.WriteLine(p.StartInfo.Arguments +
                                  pipeServer.GetClientHandleAsString());

                pipeServer.DisposeLocalCopyOfClientHandle();

                try
                {
                    using (StreamWriter sw = new StreamWriter(pipeServer))
                    {
                        sw.AutoFlush = true;
                        await sw.WriteLineAsync("SYNC");

                        pipeServer.WaitForPipeDrain();
                        await sw.WriteLineAsync(value);
                    }
                }
                catch (IOException e)
                {
                    Console.WriteLine("[SERVER] Error: {0}", e.Message);
                }
            }
        }
예제 #27
0
    public static void ServerPInvokeChecks()
    {
        // calling every API related to server and client to detect any bad PInvokes
        using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.Out))
        {
            Task clientTask = StartClientAsync(PipeDirection.In, server.ClientSafePipeHandle);

            Console.WriteLine("server.CanRead = {0}", server.CanRead);
            Console.WriteLine("server.CanSeek = {0}", server.CanSeek);
            Console.WriteLine("server.CanTimeout = {0}", server.CanTimeout);
            Console.WriteLine("server.CanWrite = {0}", server.CanWrite);
            Console.WriteLine("server.GetClientHandleAsString() = {0}", server.GetClientHandleAsString());
            Console.WriteLine("server.IsAsync = {0}", server.IsAsync);
            Console.WriteLine("server.IsConnected = {0}", server.IsConnected);
            Console.WriteLine("server.OutBufferSize = {0}", server.OutBufferSize);
            Console.WriteLine("server.ReadMode = {0}", server.ReadMode);
            Console.WriteLine("server.SafePipeHandle = {0}", server.SafePipeHandle);
            Console.WriteLine("server.TransmissionMode = {0}", server.TransmissionMode);
            server.Write(new byte[] { 123 }, 0, 1);
            server.WriteAsync(new byte[] { 124 }, 0, 1).Wait();
            server.Flush();
            Console.WriteLine("Waiting for Pipe Drain.");
            server.WaitForPipeDrain();
            clientTask.Wait();
            server.DisposeLocalCopyOfClientHandle();
        }
        using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.In))
        {
            Task clientTask = StartClientAsync(PipeDirection.Out, server.ClientSafePipeHandle);

            Console.WriteLine("server.InBufferSize = {0}", server.InBufferSize);
            byte[] readData = new byte[] { 0, 1 };
            server.Read(readData, 0, 1);
            server.ReadAsync(readData, 1, 1).Wait();
            Assert.Equal(123, readData[0]);
            Assert.Equal(124, readData[1]);
        }
    }
예제 #28
0
        /// <summary>
        /// 匿名管道服务端
        /// </summary>
        static void AnonymousPipeServer()
        {
            var pipeClient = new Process();

            pipeClient.StartInfo.FileName = @"D:\CSharpCode\MyDemo\ConsoleApp2\bin\Debug\ConsoleApp2.exe";

            using (var pipeServer = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
            {
                Console.WriteLine($"[SERVER] Current TransmissionMode: {pipeServer.TransmissionMode}");

                pipeClient.StartInfo.Arguments       = pipeServer.GetClientHandleAsString();
                pipeClient.StartInfo.UseShellExecute = false;
                pipeClient.Start();

                pipeServer.DisposeLocalCopyOfClientHandle();

                try
                {
                    using (var sw = new StreamWriter(pipeServer))
                    {
                        sw.AutoFlush = true;
                        sw.WriteLine("SYNC");
                        pipeServer.WaitForPipeDrain();
                        Console.WriteLine("[SERVER] Enter text:");
                        sw.WriteLine(Console.ReadLine());
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }

            pipeClient.WaitForExit();
            pipeClient.Close();
            Console.WriteLine($"[SERVER] Client quit. Server terminating.");
        }
        private void SetupAnonymousPipes()
        {
            _pipeClient.StartInfo.FileName = "Render.exe";

            _pipeServerStream = new AnonymousPipeServerStream(
                PipeDirection.Out,
                HandleInheritability.Inheritable);

            // Pass the client process a handle to the server.
            _pipeClient.StartInfo.Arguments       = _pipeServerStream.GetClientHandleAsString();
            _pipeClient.StartInfo.UseShellExecute = false;
            _pipeClient.Start();

            _pipeServerStream.DisposeLocalCopyOfClientHandle();

            _streamWriter = new StreamWriter(_pipeServerStream)
            {
                AutoFlush = true
            };

            _streamWriter.WriteLine("[SYNC]");
            _pipeServerStream.WaitForPipeDrain();
        }
예제 #30
0
 void DoSend()
 {
     using (StreamWriter sw = new StreamWriter(_writePipeServerStream))
     {
         while (!_stop)
         {
             try
             {
                 _autoResetEvent.Reset();
                 while (_messageConcurrentQueue.TryDequeue(out var msg))
                 {
                     sw.WriteLine(msg);
                     sw.Flush();
                     _writePipeServerStream.WaitForPipeDrain();
                 }
                 _autoResetEvent.WaitOne(1000);
             }
             catch (Exception exception)
             {
                 Trace.TraceError("[[MSP-SERVER-W]]" + exception);
             }
         }
     }
 }
예제 #31
0
        public static void ServerReadOnlyThrows()
        {
            using (AnonymousPipeServerStream server = new AnonymousPipeServerStream(PipeDirection.In))
            {
                Assert.Throws<NotSupportedException>(() => server.Write(new byte[5], 0, 5));

                Assert.Throws<NotSupportedException>(() => server.WriteByte(123));

                Assert.Throws<NotSupportedException>(() => server.Flush());

                Assert.Throws<NotSupportedException>(() => server.OutBufferSize);

                Assert.Throws<NotSupportedException>(() => server.WaitForPipeDrain());

                Assert.Throws<NotSupportedException>(() => NotReachable(server.WriteAsync(new byte[5], 0, 5)));
            }
        }