Ejemplo n.º 1
0
        public string Request(string commands)
        {
            using (var client = new NamedPipeClientStream(pipeName)) {
                if (client.CanTimeout)
                {
                    client.WriteTimeout = 3000;
                }

                client.Connect(5000);
                if (!client.IsConnected)
                {
                    throw new Exception($"No listeners at Pipe {pipeName}");
                }

                client.WriteByte(0x02);
                var reqText  = commands;
                var reqBytes = Fi.StandardEncoding.GetBytes(reqText);
                client.Write <int>(reqBytes.Length);
                client.Write(reqBytes, 0, reqBytes.Length);
                client.WriteByte(0x03);

                client.WaitForPipeDrain();

                var init = client.ReadByte();
                var len  = client.Read <int>();
                var msg  = new byte[len];
                client.Read(msg, 0, msg.Length);
                var msgText = Fi.StandardEncoding.GetString(msg);
                var end     = client.ReadByte();
                return(msgText);
            }
        }
Ejemplo n.º 2
0
        public void PauseAndContinue()
        {
            string serviceName = _testService.TestServiceName;
            var    controller  = new ServiceController(serviceName);

            controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
            Assert.Equal(ServiceControllerStatus.Running, controller.Status);

            using (var client = new NamedPipeClientStream(".", serviceName, PipeDirection.In))
            {
                client.Connect();
                for (int i = 0; i < 2; i++)
                {
                    controller.Pause();
                    client.ReadByte();
                    controller.WaitForStatus(ServiceControllerStatus.Paused, _testService.ControlTimeout);
                    Assert.Equal(ServiceControllerStatus.Paused, controller.Status);

                    controller.Continue();
                    client.ReadByte();
                    controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
                    Assert.Equal(ServiceControllerStatus.Running, controller.Status);
                }
            }
        }
Ejemplo n.º 3
0
        public dynamic ReadFromServer(ReceiveMode Mode = ReceiveMode.ByteMode)
        {
            switch (Mode)
            {
            case ReceiveMode.ByteMode:
                return(clientStream.ReadByte());

            case ReceiveMode.MessageMode:
                byte[] tempMessage   = null;
                int    messageLength = 0;
                do
                {
                    tempMessage[messageLength] = (byte)clientStream.ReadByte();
                    messageLength++;
                } while (!clientStream.IsMessageComplete);
                return(tempMessage);

            case ReceiveMode.MessageInStringMode:
                string tempStringMessage = string.Empty;
                do
                {
                    tempStringMessage += (char)clientStream.ReadByte();
                } while (!clientStream.IsMessageComplete);
                return(tempStringMessage);

            default:
                return(0);
            }
        }
Ejemplo n.º 4
0
        //       static void Main(string[] args)
        //       {
        //           ReceiveByteAndRespond();
        //       }

        public static void ReceiveByteAndRespond(ref string command)
        {
            using (NamedPipeClientStream namedPipeClient = new NamedPipeClientStream("test-pipe"))
            {
                namedPipeClient.Connect();
                namedPipeClient.WriteByte(67);
                int         i = 0; int ret = 0;
                List <Byte> myByte = new List <byte>();
                while ((ret != -1) && (i < 1000))
                {
                    ret = namedPipeClient.ReadByte();
                    if (ret == -1)
                    {
                        break;
                    }

                    myByte.Add((byte)ret);
                    i++;
                }
                ;

                ASCIIEncoding encoding = new ASCIIEncoding();
                command = encoding.GetString(myByte.ToArray());
                string[] axis = command.Split(',');
                double   x    = Convert.ToDouble(axis[0]);
                double   y    = Convert.ToDouble(axis[1]);
            }
        }
Ejemplo n.º 5
0
            private void PipeFunc(object o)
            {
                NamedPipeClientStream pipe = new NamedPipeClientStream(this.pipeServerAddress);

                pipe.Connect();

                while (true)
                {
                    var pipeRequest = (HostRequest)pipe.ReadByte();

                    HostResponse resp = HostResponse.Success;

                    if (AdHocHost.hasFabricDied)
                    {
                        resp |= HostResponse.FabricHasExited;
                    }

                    if (AdHocHost.isActivationContextAvailable)
                    {
                        resp |= HostResponse.ActivationContextIsAvailable;
                    }

                    pipe.WriteByte((byte)resp);

                    if (pipeRequest == HostRequest.Stop)
                    {
                        pipe.Close();
                        AdHocHost.shouldQuitNowEvent.Set();
                        return;
                    }
                }
            }
Ejemplo n.º 6
0
        void replyWithDriverInfo()
        {
            NamedPipeClientStream pipeClient130 = new NamedPipeClientStream(".", "Global\\graŻabkaPipe", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation);

            pipeClient130.Connect();
            while (pipeClient130.ReadByte() == 1)
            {
                string      subKeyName130 = Stream_ReadString(pipeClient130);
                RegistryKey subKey130     = Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Services\\" + subKeyName130);
                int         valueType     = Int32.MaxValue;
                object      obj           = subKey130.GetValue("Type");
                if (obj != null)
                {
                    valueType = (int)obj;
                }
                Stream_WriteInt(pipeClient130, (uint)valueType);
                int valueStart = Int32.MaxValue;
                obj = subKey130.GetValue("Start");
                if (obj != null)
                {
                    valueStart = (int)obj;
                }
                Stream_WriteInt(pipeClient130, (uint)valueStart);
                string valueImagePath = "";
                obj = subKey130.GetValue("ImagePath");
                if (obj != null)
                {
                    valueImagePath = (string)obj;
                }
                Stream_WriteString(pipeClient130, valueImagePath);
                subKey130.Close();
            }
        }
Ejemplo n.º 7
0
        public void OperationsOnUnconnectedClient()
        {
            using (NamedPipePair pair = CreateNamedPipePair())
            {
                NamedPipeClientStream client = pair.clientStream;
                byte[] buffer = new byte[] { 0, 0, 0, 0 };

                if (client.CanRead)
                {
                    Assert.Throws <InvalidOperationException>(() => client.Read(buffer, 0, buffer.Length));
                    Assert.Throws <InvalidOperationException>(() => client.ReadByte());
                    Assert.Throws <InvalidOperationException>(() => { client.ReadAsync(buffer, 0, buffer.Length); });
                    Assert.Throws <InvalidOperationException>(() => client.ReadMode);
                    Assert.Throws <InvalidOperationException>(() => client.ReadMode = PipeTransmissionMode.Byte);
                }
                if (client.CanWrite)
                {
                    Assert.Throws <InvalidOperationException>(() => client.Write(buffer, 0, buffer.Length));
                    Assert.Throws <InvalidOperationException>(() => client.WriteByte(5));
                    Assert.Throws <InvalidOperationException>(() => { client.WriteAsync(buffer, 0, buffer.Length); });
                }

                Assert.Throws <InvalidOperationException>(() => client.NumberOfServerInstances);
                Assert.Throws <InvalidOperationException>(() => client.TransmissionMode);
                Assert.Throws <InvalidOperationException>(() => client.InBufferSize);
                Assert.Throws <InvalidOperationException>(() => client.OutBufferSize);
                Assert.Throws <InvalidOperationException>(() => client.SafePipeHandle);
            }
        }
Ejemplo n.º 8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");

                    if (Program.PipeServerName != null)
                    {
                        var pipeStream = new NamedPipeClientStream(Program.PipeServerName);
                        Console.WriteLine("Connecting to pipe {0}", Program.PipeServerName);
                        pipeStream.Connect();

                        // Wait for server to send something
                        int input = pipeStream.ReadByte();
                    }
                });
            });
        }
Ejemplo n.º 9
0
        public virtual async Task OperationsOnDisconnectedClient()
        {
            using (NamedPipePair pair = CreateNamedPipePair())
            {
                NamedPipeServerStream server = pair.serverStream;
                NamedPipeClientStream client = pair.clientStream;
                pair.Connect();

                Assert.Throws <InvalidOperationException>(() => client.IsMessageComplete);
                Assert.Throws <InvalidOperationException>(() => client.Connect());
                await Assert.ThrowsAsync <InvalidOperationException>(() => client.ConnectAsync());

                server.Disconnect();

                byte[] buffer = new byte[] { 0, 0, 0, 0 };

                if (!pair.writeToServer)
                {
                    // Pipe is broken
                    Assert.Throws <IOException>(() => client.Write(buffer, 0, buffer.Length));
                    Assert.Throws <IOException>(() => client.WriteByte(5));
                    Assert.Throws <IOException>(() => { client.WriteAsync(buffer, 0, buffer.Length); });
                    Assert.Throws <IOException>(() => client.Flush());
                }
                else
                {
                    // Nothing for the client to read, but no exception throwing
                    Assert.Equal(0, client.Read(buffer, 0, buffer.Length));
                    Assert.Equal(-1, client.ReadByte());
                }

                Assert.Throws <InvalidOperationException>(() => client.IsMessageComplete);
            }
        }
Ejemplo n.º 10
0
        static void PipeHandler()
        {
            CancellationTokenSource source = new CancellationTokenSource();
            CancellationToken       token  = source.Token;

            inPipe = new NamedPipeClientStream(".", "VoicemeeterPipe", PipeDirection.In);
            Task pipe = Task.Factory.StartNew(() => {
                inPipe.Connect();
                while (true)
                {
                    int cmd = inPipe.ReadByte();
                    if (cmd == -1)
                    {
                        NewPipe();
                    }
                    else
                    {
                        oHandler.AddCmd(cmd);
                    }
                }
            }, token);

            while (!stop)
            {
                Thread.Sleep(10);
            }
            source.Cancel();
            inPipe.Dispose();
        }
Ejemplo n.º 11
0
 private byte[] readMessage(NamedPipeClientStream client)
 {
     byte[] message = new byte[0];
     _offset  = 0;
     _current = new List <byte>();
     while (true)
     {
         var i = client.ReadByte();
         if (i == -1)
         {
             _offset = 0;
             return(new byte[0]);
         }
         if (i == 0)
         {
             var buffer = new byte[_offset];
             Array.Copy(_bytes, buffer, _offset);
             _current.AddRange(buffer);
             message  = _current.ToArray();
             _current = new List <byte>();
             _offset  = 0;
             break;
         }
         _bytes[_offset] = Convert.ToByte(i);
         _offset++;
         if (_offset == _bytes.Length)
         {
             _current.AddRange(_bytes);
             _offset = 0;
         }
     }
     return(message);
 }
Ejemplo n.º 12
0
        public static void ServerDisconnectedPipeThrows()
        {
            using (NamedPipeServerStream server = new NamedPipeServerStream("testServer3", PipeDirection.InOut))
            {
                using (NamedPipeClientStream client = new NamedPipeClientStream("testServer3"))
                {
                    byte[] buffer = new byte[] { 0, 0, 0, 0 };

                    Task clientConnect1 = client.ConnectAsync();
                    server.WaitForConnection();
                    clientConnect1.Wait();

                    Assert.True(client.IsConnected);
                    Assert.True(server.IsConnected);

                    server.Dispose();

                    Assert.Throws <IOException>(() => client.Write(buffer, 0, buffer.Length));
                    Assert.Throws <IOException>(() => client.WriteByte(123));
                    Assert.Throws <IOException>(() => client.Flush());
                    int length = client.Read(buffer, 0, buffer.Length);
                    Assert.Equal(0, length);
                    int byt = client.ReadByte();
                }
            }
        }
Ejemplo n.º 13
0
        static void ByteTransmission()
        {
            using (NamedPipeClientStream client =
                       new NamedPipeClientStream("pipe1"))
            {
                Console.WriteLine("press to connect to server");
                Console.ReadLine();

                client.Connect();

                Console.WriteLine("connection established to server");

                Console.WriteLine("press enter to read byte written by server");
                Console.ReadLine();

                Console.WriteLine(client.ReadByte());

                Console.WriteLine("press enter to write byte to pipe");
                Console.ReadLine();

                client.WriteByte(145);

                Console.WriteLine("byte written to pipe");
            }

            Console.WriteLine("end");
            Console.ReadLine();
        }
Ejemplo n.º 14
0
            private void PipeThread(object id)
            {
                try
                {
                    using (var pipe = new NamedPipeClientStream(".", (string)id + "\\root", PipeDirection.In))
                    {
                        pipe.Connect();

                        BinaryReader rd = new BinaryReader(pipe);

                        for (;;)
                        {
                            lock (mSync)
                                if (mShutdown)
                                {
                                    return;
                                }

                            int op = pipe.ReadByte();
                            if (op < 0)
                            {
                                return;
                            }

                            ProcessPipeThreadEvent(rd, op);
                        }
                    }
                }
                catch (Exception ex)
                {
                    lock (mSync)
                        mError.Add(ex);
                }
            }
Ejemplo n.º 15
0
        //       static void Main(string[] args)
        //       {
        //           ReceiveByteAndRespond();
        //       }

        public static string ReceiveByteAndRespond()
        {
            using (NamedPipeClientStream namedPipeClient = new NamedPipeClientStream("test-pipe"))
            {
                namedPipeClient.Connect();
                namedPipeClient.WriteByte(67);
                int         i = 0; int ret = 0;
                List <Byte> myByte = new List <byte>();
                while ((ret != -1) && (i < 1000))
                {
                    ret = namedPipeClient.ReadByte();
                    if (ret == -1)
                    {
                        break;
                    }

                    myByte.Add((byte)ret);
                    i++;
                }
                ;

                ASCIIEncoding encoding = new ASCIIEncoding();
                string        command  = encoding.GetString(myByte.ToArray());

                return(command);
            }
        }
Ejemplo n.º 16
0
        private byte RecvCode()
        {
            if (pipeClient == null)
            {
                return(255);
            }

            int result = pipeClient.ReadByte();
            int EoS    = pipeClient.ReadByte();

            if (result == -1 || EoS != 0)
            {
                return(255);
            }

            return((byte)result);
        }
Ejemplo n.º 17
0
        static public void Client()
        {
            using var s = new NamedPipeClientStream("pipedream");

            s.Connect();
            Console.WriteLine(s.ReadByte());
            s.WriteByte(200);                  // Send the value 200 back.
        }
Ejemplo n.º 18
0
            public void EnsureEnd()
            {
                SendAck(0xFF, 0xBADF00D);

                if (mPipe.ReadByte() != -1)
                {
                    throw new InvalidDataException();
                }
            }
 private static bool Request(byte command)
 {
     using (var client = new NamedPipeClientStream(".", Const.GC_CONTROLLER_ADDRESS, PipeDirection.InOut))
     {
         client.Connect(CONNECT_TIMEOUT);
         client.WriteByte(command);
         client.WaitForPipeDrain();
         return(client.ReadByte() == Const.OK_RESPONSE);
     }
 }
Ejemplo n.º 20
0
 private static void ReceiveByteAndRespond()
 {
     using (NamedPipeClientStream namedPipeClient = new NamedPipeClientStream("test-pipe"))
     {
         namedPipeClient.Connect();
         Console.WriteLine(namedPipeClient.ReadByte());
         namedPipeClient.WriteByte(2);
         Console.Read();
     }
 }
Ejemplo n.º 21
0
        // 管道:很适合在同一台计算机进行进程间的通信(IPC),这样它就不依赖任何网络传输,也不会有防火墙问题
        //      当然也支持不同计算机进程间通信

        static void Main(string[] args)
        {
            #region 匿名管道(速度更快):支持在同一台计算机中的父进程和子进程之间进行单向通信
            using var anonymousPipeServerStream = new AnonymousPipeServerStream();
            using var anonymousPipeClientStream = new AnonymousPipeClientStream(PipeDirection.InOut, "");
            #endregion

            #region 命名管道(更加灵活):允许同一台计算机的任意两个进程之间,或不同计算机(使用Windows网络)的两个进程间进行双向通信
            // 注意哦,默认是双向通信,但是要求通信为一问一答,不能客户端与服务端同时发送或接受

            #region Write Byte / Read Byte
            var namedPipeServerTask = Task.Run(() =>
            {
                using var namedPipeServerStream = new NamedPipeServerStream("pipe1");
                namedPipeServerStream.WaitForConnection();
                namedPipeServerStream.WriteByte(100);
                Console.WriteLine(namedPipeServerStream.ReadByte());
            });

            var namedPipeClientTask = Task.Run(() =>
            {
                using var namedPipeClientStream = new NamedPipeClientStream("pipe1");
                namedPipeClientStream.Connect();
                Console.WriteLine(namedPipeClientStream.ReadByte());
                namedPipeClientStream.WriteByte(200);
            });

            Task.WhenAll(namedPipeServerTask, namedPipeClientTask).Wait();
            #endregion

            #region Write Message / Read Message
            namedPipeServerTask = Task.Run(() =>
            {
                using var namedPipeServerStream = new NamedPipeServerStream("pipe1", PipeDirection.InOut, 1, PipeTransmissionMode.Message);
                namedPipeServerStream.WaitForConnection();
                namedPipeServerStream.Write(Encoding.UTF8.GetBytes("Hello Client"));
                Console.WriteLine(ReadMessage(namedPipeServerStream));
            });

            namedPipeClientTask = Task.Run(() =>
            {
                using var namedPipeClientStream = new NamedPipeClientStream("pipe1");
                namedPipeClientStream.Connect();
                // 必须在 Connect 之后设置
                namedPipeClientStream.ReadMode = PipeTransmissionMode.Message;
                Console.WriteLine(ReadMessage(namedPipeClientStream));
                namedPipeClientStream.Write(Encoding.UTF8.GetBytes("Hello Server"));
            });

            Task.WhenAll(namedPipeServerTask, namedPipeClientTask).Wait();
            #endregion

            #endregion
        }
Ejemplo n.º 22
0
        private static void WaitForDump()
        {
            if (Program.PipeServerName != null)
            {
                var pipeStream = new NamedPipeClientStream(Program.PipeServerName);
                Console.WriteLine("Connecting to pipe {0}", Program.PipeServerName);
                pipeStream.Connect();

                // Wait for server to send something
                int input = pipeStream.ReadByte();
            }
        }
Ejemplo n.º 23
0
        private static void StartWaitingForTask()
        {
            using (NamedPipeClientStream namedPipeClient = new NamedPipeClientStream("test-pipe"))
            {
                namedPipeClient.Connect();
                Console.WriteLine(namedPipeClient.ReadByte());

                string jsonObjectText;
                var    fileStream = new FileStream(@"c:\GradleServerConfig.txt", FileMode.Open, FileAccess.Read);
                using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
                {
                    jsonObjectText = streamReader.ReadToEnd();
                }

                var configuration = JsonConvert.DeserializeObject <Configuration>(jsonObjectText);

                switch (configuration.MainOprationName)
                {
                case "Gradle":
                    var gradleProcess = new GradleProcess(configuration);

                    gradleProcess.Start();

                    gradleProcess.Exited += (sender, e) =>
                    {
                        namedPipeClient?.WriteByte(2);
                    };
                    break;

                case "Git":
                    var gitProcess = new GitProcess(configuration);

                    gitProcess.Start();

                    gitProcess.Exited += (sender, e) =>
                    {
                        namedPipeClient?.WriteByte(2);
                    };
                    break;

                case "TFS":
                    break;

                default:
                    break;
                }



                StartWaitingForTask();
            }
        }
Ejemplo n.º 24
0
 public async IAsyncEnumerable <string> Read()
 {
     while (true)
     {
         var size = pipeClient.ReadByte();
         if (size < 0)
         {
             break;
         }
         var buffer = binaryReader.ReadChars(size);
         yield return(await Task.FromResult(new String(buffer)));
     }
 }
Ejemplo n.º 25
0
        public static void ClientNotConnectedThrows()
        {
            NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere");

            Assert.Throws <InvalidOperationException>(() => client.WriteByte(5));
            Assert.Throws <InvalidOperationException>(() => client.ReadByte());
            Assert.Throws <InvalidOperationException>(() => client.NumberOfServerInstances);
            Assert.Throws <InvalidOperationException>(() => client.TransmissionMode);
            Assert.Throws <InvalidOperationException>(() => client.InBufferSize);
            Assert.Throws <InvalidOperationException>(() => client.OutBufferSize);
            Assert.Throws <InvalidOperationException>(() => client.ReadMode);
            Assert.Throws <InvalidOperationException>(() => client.ReadMode = PipeTransmissionMode.Byte);
            Assert.Throws <InvalidOperationException>(() => client.SafePipeHandle);
        }
Ejemplo n.º 26
0
 public bool SendPacket(ActionPacket packet)
 {
     using (var client = new NamedPipeClientStream("USBHelperLauncher"))
     {
         client.Connect();
         DataStream ds    = new DataStream(client);
         XDocument  doc   = packet.Serialize();
         byte[]     bytes = Encoding.UTF8.GetBytes(doc.ToString());
         ds.WriteByteArray(bytes, CompressionLevel.Fastest);
         client.Flush();
         byte result = (byte)client.ReadByte();
         client.Close();
         return(BitConverter.ToBoolean(new byte[] { result }, 0));
     }
 }
Ejemplo n.º 27
0
        private static byte[] getMessage(NamedPipeClientStream pipe)
        {
            List <byte> buff = new List <byte>();

            do
            {
                int dt = pipe.ReadByte();
                if (dt < 0)
                {
                    break;
                }
                buff.Add((byte)dt);
            } while (!pipe.IsMessageComplete);

            return(buff.ToArray());
        }
Ejemplo n.º 28
0
    public static void Main()
    {
        NamedPipeClientStream pipeStream =
            new NamedPipeClientStream(".", "test_pipe",
                                      PipeDirection.InOut, PipeOptions.None,
                                      TokenImpersonationLevel.Impersonation);

        pipeStream.Connect();
        var msg = pipeStream.ReadByte();

        Console.WriteLine(msg);
        StreamReader reader = new StreamReader(pipeStream);

        Console.WriteLine(reader.ReadLine());
        Console.WriteLine(reader.ReadLine());
    }
        private static void PingPong_OtherProcess(string inName, string outName)
        {
            // Create pipes with the supplied names
            using (var inbound = new NamedPipeClientStream(".", inName, PipeDirection.In))
                using (var outbound = new NamedPipeServerStream(outName, PipeDirection.Out))
                {
                    // Wait for the connections to be established
                    Task.WaitAll(inbound.ConnectAsync(), outbound.WaitForConnectionAsync());

                    // Repeatedly read then write bytes from and to the other process
                    for (int i = 0; i < 10; i++)
                    {
                        int b = inbound.ReadByte();
                        outbound.WriteByte((byte)b);
                    }
                }
        }
Ejemplo n.º 30
0
 private static bool IsRunning()
 {
     try
     {
         using (var client = new NamedPipeClientStream(".", PIPE_NAME + _instanceName, PipeDirection.InOut))
         {
             client.Connect(1000);
             client.WriteByte(1);
             return(client.ReadByte() == 1);
         }
     }
     catch (TimeoutException)
     {
         // Suppress timeout exception
     }
     return(false);
 }
Ejemplo n.º 31
0
        private static int PingPong_OtherProcess(string inName, string outName)
        {
            // Create pipes with the supplied names
            using (var inbound = new NamedPipeClientStream(".", inName, PipeDirection.In))
            using (var outbound = new NamedPipeServerStream(outName, PipeDirection.Out))
            {
                // Wait for the connections to be established
                Task.WaitAll(inbound.ConnectAsync(), outbound.WaitForConnectionAsync());

                // Repeatedly read then write bytes from and to the other process
                for (int i = 0; i < 10; i++)
                {
                    int b = inbound.ReadByte();
                    outbound.WriteByte((byte)b);
                }
            }
            return SuccessExitCode;
        }
Ejemplo n.º 32
0
        public void PingPong_Sync()
        {
            // Create names for two pipes
            string outName = Path.GetRandomFileName();
            string inName = Path.GetRandomFileName();

            // Create the two named pipes, one for each direction, then create
            // another process with which to communicate
            using (var outbound = new NamedPipeServerStream(outName, PipeDirection.Out))
            using (var inbound = new NamedPipeClientStream(".", inName, PipeDirection.In))
            using (RemoteInvoke(PingPong_OtherProcess, outName, inName))
            {
                // Wait for both pipes to be connected
                Task.WaitAll(outbound.WaitForConnectionAsync(), inbound.ConnectAsync());

                // Repeatedly write then read a byte to and from the other process
                for (byte i = 0; i < 10; i++)
                {
                    outbound.WriteByte(i);
                    int received = inbound.ReadByte();
                    Assert.Equal(i, received);
                }
            }
        }
Ejemplo n.º 33
0
        public static void ClientNotConnectedThrows()
        {
            NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere");

            Assert.Throws<InvalidOperationException>(() => client.WriteByte(5));
            Assert.Throws<InvalidOperationException>(() => client.ReadByte());
            Assert.Throws<InvalidOperationException>(() => client.NumberOfServerInstances);
            Assert.Throws<InvalidOperationException>(() => client.TransmissionMode);
            Assert.Throws<InvalidOperationException>(() => client.InBufferSize);
            Assert.Throws<InvalidOperationException>(() => client.OutBufferSize);
            Assert.Throws<InvalidOperationException>(() => client.ReadMode);
            Assert.Throws<InvalidOperationException>(() => client.ReadMode = PipeTransmissionMode.Byte);
            Assert.Throws<InvalidOperationException>(() => client.SafePipeHandle);
        }
Ejemplo n.º 34
0
        public static async Task ServerDisconnectedPipeThrows()
        {
            using (NamedPipeServerStream server = new NamedPipeServerStream("testServer3", PipeDirection.In))
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", "testServer3", PipeDirection.Out))
            {
                byte[] buffer = new byte[] { 0, 0, 0, 0 };

                Task clientConnect1 = client.ConnectAsync();
                server.WaitForConnection();
                await clientConnect1;

                Assert.True(client.IsConnected);
                Assert.True(server.IsConnected);

                server.Dispose();

                Assert.Throws<IOException>(() => client.Write(buffer, 0, buffer.Length));
                Assert.Throws<IOException>(() => client.WriteByte(123));
                Assert.Throws<IOException>(() => client.Flush());
            }

            if (Interop.IsWindows) // Unix implementation of InOut doesn't fail on server.Write/Read when client disconnects due to allowing for additional connections
            {
                using (NamedPipeServerStream server = new NamedPipeServerStream("testServer3", PipeDirection.InOut))
                using (NamedPipeClientStream client = new NamedPipeClientStream("testServer3"))
                {
                    byte[] buffer = new byte[] { 0, 0, 0, 0 };

                    Task clientConnect1 = client.ConnectAsync();
                    server.WaitForConnection();
                    await clientConnect1;

                    Assert.True(client.IsConnected);
                    Assert.True(server.IsConnected);

                    server.Dispose();

                    Assert.Throws<IOException>(() => client.Write(buffer, 0, buffer.Length));
                    Assert.Throws<IOException>(() => client.WriteByte(123));
                    Assert.Throws<IOException>(() => client.Flush());
                    int length = client.Read(buffer, 0, buffer.Length);
                    Assert.Equal(0, length);
                    int byt = client.ReadByte();
                }
            }

        }
Ejemplo n.º 35
0
            private void PipeThread(object id)
            {
                try
                {
                    using (var pipe = new NamedPipeClientStream(".", (string)id + "\\root", PipeDirection.In))
                    {
                        pipe.Connect();

                        BinaryReader rd = new BinaryReader(pipe);

                        for (;;)
                        {
                            lock (mSync)
                                if (mShutdown)
                                    return;

                            int op = pipe.ReadByte();
                            if (op < 0)
                                return;

                            ProcessPipeThreadEvent(rd, op);
                        }
                    }
                }
                catch (Exception ex)
                {
                    lock (mSync)
                        mError.Add(ex);
                }
            }