Пример #1
0
            using (NamedPipeServerStream serverPipeStream = new NamedPipeServerStream("SamplePipe"))
            {
                Console.WriteLine("Waiting for client to connect.");
                serverPipeStream.WaitForConnection();
                Console.WriteLine("Connected to client.");
                byte[] bytes = Encoding.UTF8.GetBytes("Hello World\n");
                while (true)
                {
                    serverPipeStream.Write(bytes, 0, bytes.Length);
                    serverPipeStream.Flush(); //to get sure it is send immediatelly
                    Thread.Sleep(1000);
                }
            }
        }
    }
}
Пример #2
0
        static void Test2()
        {
            NamedPipeServerStream stream = new NamedPipeServerStream("MaxUnityBridge");
            stream.WaitForConnection();

            do
            {
                byte[] data = new byte[4];
                stream.Read(data, 0, 4);

                System.Console.WriteLine(string.Format("Received: {0} {1} {2} {3}", data[0], data[1], data[2], data[3]));

                stream.Write(new byte[] { 5, 6, 7, 8 }, 0, 4);

                System.Console.WriteLine("Sent: 5 6 7 8");

                stream.Flush();
                stream.WaitForPipeDrain();


            } while (true);
        }
Пример #3
0
        void DoListen()
        {
            while (true)
            using (NamedPipeServerStream pipeServer = new NamedPipeServerStream (pipePath, PipeDirection.InOut, numPipeThreads, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, (int)Protocol.MaxMessageLength, (int)Protocol.MaxMessageLength)) {
                Console.WriteLine ("Waiting for client on path " + pipePath);
                pipeServer.WaitForConnection ();

                Console.WriteLine ("Client connected");

                ServerConnection conn;
                if (!AcceptClient (pipeServer, out conn)) {
                    Console.WriteLine ("Client rejected");
                    pipeServer.Disconnect ();
                    continue;
                }

                pipeServer.Flush ();
                pipeServer.WaitForPipeDrain ();

                if (NewConnection != null)
                    NewConnection (conn);

                while (conn.IsConnected)
                    conn.Iterate ();

                pipeServer.Disconnect ();
            }
        }
Пример #4
0
        private static BuildResult OutOfProcessBuild (Dictionary<string, object> arguments, int startupTimeoutMs = 5000) {
            var jss = new JavaScriptSerializer {
                MaxJsonLength = 1024 * 1024 * 64
            };

            var argsJson = jss.Serialize(arguments);
            var pipeId = String.Format("JSIL.Build{0:X4}", (new Random()).Next());

            Console.Error.WriteLine("// Starting out-of-process solution build with ID '{0}'...", pipeId);

            using (var pipe = new NamedPipeServerStream(
                pipeId, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous
            )) {
                var psi = new ProcessStartInfo {
                    FileName = Process.GetCurrentProcess().MainModule.FileName,
                    Arguments = String.Format("--buildSolution {0}", pipeId),
                    WorkingDirectory = Environment.CurrentDirectory,
                    CreateNoWindow = false,
                    UseShellExecute = false,
                    ErrorDialog = false                    
                };
                var childProcess = Process.Start(psi);
                if (childProcess == null)
                    throw new InvalidOperationException("Failed to start child process");

                var connectedEvent = new ManualResetEventSlim(false);
                var exitedEvent = new ManualResetEventSlim(false);

                try {
                    var connectAR = pipe.BeginWaitForConnection((_) => connectedEvent.Set(), null);

                    try {
                        childProcess.Exited += (s, e) => exitedEvent.Set();
                        if (childProcess.HasExited)
                            exitedEvent.Set();
                    } catch {
                    }

                    WaitHandle.WaitAny(
                        new[] { connectedEvent.WaitHandle, exitedEvent.WaitHandle }, startupTimeoutMs
                    );

                    if (connectedEvent.IsSet) {
                        pipe.EndWaitForConnection(connectAR);
                    } else if (exitedEvent.IsSet) {
                        Console.Error.WriteLine("// Out-of-process solution build terminated unexpectedly with code {0}!", childProcess.ExitCode);
                        Environment.Exit(1);
                    } else {
                        Console.Error.WriteLine("// Out-of-process solution build timed out!");
                        Environment.Exit(2);
                    }

                    using (var sr = new StreamReader(pipe))
                    using (var sw = new StreamWriter(pipe)) {
                        sw.WriteLine(argsJson);
                        sw.Flush();
                        pipe.Flush();
                        pipe.WaitForPipeDrain();

                        var resultJson = sr.ReadLine();
                        var buildResult = jss.Deserialize<BuildResult>(resultJson);

                        Console.Error.WriteLine("// Out-of-process solution build completed successfully.");

                        return buildResult;
                    }
                } finally {
                    try {
                        if (!childProcess.HasExited)
                            childProcess.Kill();
                    } catch {
                    }

                    childProcess.Dispose();
                }
            }
        }
Пример #5
0
        public void ServiceRequest(NamedPipeServerStream nss)
        {
            var msgbuf = new List<byte>(8192);
            var rxbuf = new byte[256 * 1024];
            int count = 0;


            Logging.Emit("reading from client");
            do
            {
                count = nss.Read(rxbuf, msgbuf.Count, rxbuf.Length);
                if (count > 0)
                {
                    msgbuf.AddRange(rxbuf.Take(count));
                }

            } while (!nss.IsMessageComplete);

            Logging.Emit("server read  {0} bytes", msgbuf.Count);

            // deserialize message from msgbuf
            var req = CClashMessage.Deserialize<CClashRequest>(msgbuf.ToArray());
            cache.Setup(); // needed?
            Logging.Emit("processing request");
            var resp = ProcessRequest(req);
            Logging.Emit("request complete: supported={0}, exitcode={1}", resp.supported, resp.exitcode);
            var tx = resp.Serialize();
            nss.Write(tx, 0, tx.Length);
            nss.Flush();
            Logging.Emit("server written {0} bytes", tx.Length);

            nss.WaitForPipeDrain();
            nss.Disconnect();
            
            Logging.Emit("request done");
        }
Пример #6
0
 private void BeginWriteCallback(IAsyncResult iar)
 {
     pipeServer = (NamedPipeServerStream)iar.AsyncState;
     pipeServer.EndWrite(iar);
     sendRequested = false;
     pipeServer.Flush();
 }
Пример #7
0
    public static async Task ServerPInvokeChecks()
    {
        // calling every API related to server and client to detect any bad PInvokes
        using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.Out))
        {
            Task clientTask = Task.Run(() => StartClient(PipeDirection.In));
            server.WaitForConnection();

            Assert.False(server.CanRead);
            Assert.False(server.CanSeek);
            Assert.False(server.CanTimeout);
            Assert.True(server.CanWrite);
            Assert.False(server.IsAsync);
            Assert.True(server.IsConnected);
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                Assert.Equal(0, server.OutBufferSize);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                Assert.True(server.OutBufferSize > 0);
            }
            else
            {
                Assert.Throws<PlatformNotSupportedException>(() => 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);
            await server.WriteAsync(new byte[] { 124 }, 0, 1);
            server.Flush();
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                server.WaitForPipeDrain();
            }
            else
            {
                Assert.Throws<PlatformNotSupportedException>(() => server.WaitForPipeDrain());
            }

            await clientTask;
        }

        using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.In))
        {
            Task clientTask = Task.Run(() => StartClient(PipeDirection.Out));
            server.WaitForConnection();

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                Assert.Equal(0, server.InBufferSize);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                Assert.True(server.InBufferSize > 0);
            }
            else
            {
                Assert.Throws<PlatformNotSupportedException>(() => 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]);
        }
    }
Пример #8
0
        static void HandleIncomingConnection( NamedPipeServerStream server )
        {
            // This is not quite as good as it should be, but OH WELL
            //
            ThreadPool.QueueUserWorkItem( delegate
            {
                try
                {
                    using ( server )
                    {
                        StreamWriter writer = new StreamWriter( server );
                        StreamReader reader = new StreamReader( server );
                        try
                        {
                            var request = ExecuteRequest.Read( reader );
                            if ( request == null ) { return; }

                            writer.WriteLine( "{0}", Execute( request ) );
                            writer.WriteLine( "OK" );
                            writer.Flush();
                            server.Flush();
                        }
                        catch ( Exception e )
                        {
                            writer.WriteLine( "-1" );
                            writer.WriteLine( e.Message );
                            writer.Flush();
                            server.Flush();
                        }
                    }
                }
                catch ( IOException ioe )
                {
                    Tracer.WriteWarning( "IO Error communicating with client: {0}", ioe );
                }
                finally
                {
                    DecrementServers();
                }
            } );
        }
Пример #9
0
    const int BUFFER_SIZE = 4096; // 4 KB

    #endregion Fields

    #region Methods

    /// <summary>
    /// Named pipe server through BCL System.IO.Pipes
    /// </summary>
    static void BCLSystemIOPipeServer()
    {
        NamedPipeServerStream pipeServer = null;

        try
        {
            /////////////////////////////////////////////////////////////////
            // Create a named pipe.
            //

            // Prepare the pipe name
            String strPipeName = "HelloWorld";

            // Prepare the security attributes
            // Granting everyone the full control of the pipe is just for
            // demo purpose, though it creates a security hole.
            PipeSecurity pipeSa = new PipeSecurity();
            pipeSa.SetAccessRule(new PipeAccessRule("Everyone",
                PipeAccessRights.ReadWrite, AccessControlType.Allow));

            // Create the named pipe
            pipeServer = new NamedPipeServerStream(
                strPipeName,                    // The unique pipe name.
                PipeDirection.InOut,            // The pipe is bi-directional
                NamedPipeServerStream.MaxAllowedServerInstances,
                PipeTransmissionMode.Message,   // Message type pipe
                PipeOptions.None,               // No additional parameters
                BUFFER_SIZE,                    // Input buffer size
                BUFFER_SIZE,                    // Output buffer size
                pipeSa,                         // Pipe security attributes
                HandleInheritability.None       // Not inheritable
                );

            Console.WriteLine("The named pipe, {0}, is created", strPipeName);

            /////////////////////////////////////////////////////////////////
            // Wait for the client to connect.
            //

            Console.WriteLine("Waiting for the client's connection...");
            pipeServer.WaitForConnection();

            /////////////////////////////////////////////////////////////////
            // Read client requests from the pipe and write the response.
            //

            // A byte buffer of BUFFER_SIZE bytes. The buffer should be big
            // enough for ONE request from a client.

            string strMessage;
            byte[] bRequest = new byte[BUFFER_SIZE];// Client -> Server
            int cbBytesRead, cbRequestBytes;
            byte[] bReply;                          // Server -> Client
            int cbBytesWritten, cbReplyBytes;

            do
            {
                // Receive one message from the pipe.

                cbRequestBytes = BUFFER_SIZE;
                cbBytesRead = pipeServer.Read(bRequest, 0, cbRequestBytes);

                // Unicode-encode the byte array and trim all the '\0' chars
                // at the end.
                strMessage = Encoding.Unicode.GetString(bRequest).TrimEnd('\0');
                Console.WriteLine("Receives {0} bytes; Message: \"{1}\"",
                    cbBytesRead, strMessage);

                // Prepare the response.

                // '\0' is appended in the end because the client may be a
                // native C++ program.
                strMessage = "Default response from server\0";
                bReply = Encoding.Unicode.GetBytes(strMessage);
                cbReplyBytes = bReply.Length;

                // Write the response to the pipe.

                pipeServer.Write(bReply, 0, cbReplyBytes);
                // If no IO exception is thrown from Write, number of bytes
                // written (cbBytesWritten) != -1.
                cbBytesWritten = cbReplyBytes;

                Console.WriteLine("Replies {0} bytes; Message: \"{1}\"",
                    cbBytesWritten, strMessage.TrimEnd('\0'));

            }
            while (!pipeServer.IsMessageComplete);

            /////////////////////////////////////////////////////////////////
            // Flush the pipe to allow the client to read the pipe's contents
            // before disconnecting. Then disconnect the pipe.
            //

            pipeServer.Flush();
            pipeServer.Disconnect();

        }
        catch (Exception ex)
        {
            Console.WriteLine("The server throws the error: {0}", ex.Message);
        }
        finally
        {
            if (pipeServer != null)
            {
                // Close the stream.
                pipeServer.Close();
            }
        }
    }
        /// <summary>
        /// Creates a new named pipe from a Youtube video link.
        /// </summary>
        /// <param name="source">Source stream.</param>
        /// <param name="namedPipeName">Named pipe.</param>
        /// <param name="onProgress">Function executed when progress changes. Return true to cancel the operation, false to continue.</param>
        /// <param name="onFinish">Action executed when a reading operation finishes.</param>
        /// <returns>Pipe name.</returns>
        public static string NamedPipeFromStreamAsync(this Stream source, string namedPipeName, Func<float, bool> onProgress = null, Action onFinish = null)
        {
            if (source == null)
                new ArgumentNullException(nameof(source));

            Task.Factory.StartNew(() =>
            {
                using (NamedPipeServerStream target = new NamedPipeServerStream(namedPipeName))
                {
                    target.WaitForConnection();
                    target.WaitForPipeDrain();

                    int bytes, copiedBytes = 0;
                    var buffer = new byte[1024];
                    while ((bytes = source.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        target.Write(buffer, 0, bytes);
                        copiedBytes += bytes;

                        if (onProgress != null)
                        {
                            bool shouldCancel = onProgress((float)copiedBytes / source.Length);
                            if (shouldCancel)
                                break;
                        }
                    }

                    target.Flush();
                    if (onFinish != null) onFinish();
                }
            });

            return namedPipeName;
        }
Пример #11
0
    public static void ServerPInvokeChecks()
    {
        // calling every API related to server and client to detect any bad PInvokes
        using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.Out))
        {
            Task clientTask = StartClientAsync(PipeDirection.In);

            server.WaitForConnection();
            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.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();
            server.WaitForPipeDrain();
            clientTask.Wait();
        }
        using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.In))
        {
            Task clientTask = StartClientAsync(PipeDirection.Out);

            server.WaitForConnection();
            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]);
        }
    }