Exemplo n.º 1
0
        private void SendCommand(string command)
        {
            var clientStream = new NamedPipeClientStream(".", this.PipeName, PipeDirection.InOut, PipeOptions.Asynchronous);

            clientStream.Connect(500);
            clientStream.ReadMode = PipeTransmissionMode.Message;
            var commandBytes = Encoding.ASCII.GetBytes(command);

            byte[] buffer          = new byte[256];
            var    responseBuilder = new StringBuilder();

            clientStream.Write(commandBytes, 0, commandBytes.Length);

            int read = clientStream.Read(buffer, 0, buffer.Length);

            responseBuilder.Append(Encoding.ASCII.GetString(buffer, 0, read));

            while (!clientStream.IsMessageComplete)
            {
                read = clientStream.Read(buffer, 0, buffer.Length);
                responseBuilder.Append(Encoding.ASCII.GetString(buffer, 0, read));
            }

            this.ProcessResponse(responseBuilder.ToString());
        }
Exemplo n.º 2
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);
            }
        }
Exemplo n.º 3
0
        public override Dictionary <int, int> ReadState()
        {
            using (StreamWriter sw = new StreamWriter(pipeStream))
            {
                sw.AutoFlush = true;
                sw.WriteLine("R");
            }
            var values = new List <int>();

            using (StreamReader sr = new StreamReader(pipeStream))
            {
                byte[] val       = new byte[IntBytes];
                var    readBytes = 0;
                do
                {
                    pipeStream.Read(val, 0, IntBytes);
                    values.Add(System.BitConverter.ToInt32(val, 0));
                } while (readBytes == IntBytes);
            }
            var dic = new Dictionary <int, int>();

            for (int i = 0; i < values.Count() - 1; i += 2)
            {
                dic[values[i]] = values[i + 1];
            }
            return(dic);
        }
Exemplo n.º 4
0
        public void TestTwoWayReceive_XML_Unicode()
        {
            adapter.Encoding = "Unicode";
            inboundHandler.StartListener(null, new TimeSpan(0, 0, 60));

            using (NamedPipeClientStream pipeClient = new NamedPipeClientStream("localhost",
                                                                                connectionUri.Uri.AbsolutePath, PipeDirection.InOut, PipeOptions.Asynchronous))
            {
                //TODO: implement sending XML message to the inbound handler
                string xml = "<SomeTestMessage><Element1 attribute1=\"attributeValue\"></Element1><Element2>Some element content</Element2></SomeTestMessage>";

                byte[] xmlBytes = Encoding.Unicode.GetBytes(xml);

                pipeClient.Connect(10000);
                pipeClient.Write(xmlBytes, 0, xmlBytes.Count());
                //Send the EOF bytes
                //pipeClient.Write(new byte[] { 0x00, 0x00 }, 0, 2);
                pipeClient.WriteByte(0x00);
                pipeClient.WaitForPipeDrain();
                //Now we read the message in the inbound handler
                Message       msg = null;
                IInboundReply reply;
                inboundHandler.TryReceive(new TimeSpan(0, 0, 10), out msg, out reply);

                Assert.IsNotNull(msg, "Message instance was not returned");
                Assert.AreEqual(xml, GeneralTestHelper.GetBodyAsString(msg, Encoding.Unicode), "Message contents of received message is different");
                //we send the response message
                string  responseXml     = "<Response><Description>The request was successfully processed</Description></Response>";
                Message responseMessage = GeneralTestHelper.CreateMessageWithBase64EncodedBody(responseXml, Encoding.Unicode);

                byte[] inBuffer = new byte[256];
                int    bytesCountRead = 0, eofCountRead = 0;
                System.Threading.ManualResetEvent manualEvent = new System.Threading.ManualResetEvent(false);
                //We queue up the reply so that it executes from the context of another thread.
                System.Threading.ThreadPool.QueueUserWorkItem(cb =>
                {
                    //we try to read from the pipe
                    bytesCountRead = pipeClient.Read(inBuffer, 0, inBuffer.Length);
                    //read the EOF bytes.
                    byte[] eofBytes = new byte[2];
                    eofCountRead    = pipeClient.Read(eofBytes, 0, 1);

                    manualEvent.Set();
                }
                                                              );

                reply.Reply(responseMessage, new TimeSpan(0, 0, 10));
                //We wait for the event to be signalled
                manualEvent.WaitOne(10000);

                string receivedResponseXml = GeneralTestHelper.GetMessageFromArray(inBuffer, bytesCountRead - (1 - eofCountRead), Encoding.Unicode);

                Assert.AreEqual(responseXml, receivedResponseXml, "The received response is not correct");
            }
        }
Exemplo n.º 5
0
        static int Main(string[] args)
        {
            TextWriter logWriter = new StreamWriter(Environment.CurrentDirectory + "\\log.txt", true);

            try
            {
                NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "pipeServer" + args[0], PipeDirection.InOut);
#if debug
                Console.WriteLine(DateTime.Now + "|SYSLOG|=>$ " + "Connection");
#endif
                logWriter.WriteLine(DateTime.Now + "|SYSLOG|=>$ " + "Connection.... Iddentificator:" + args[0]);
                pipeClient.Connect(15000);
#if debug
                Console.WriteLine(DateTime.Now + "|SYSLOG|=>$ " + "Connected");
#endif
                logWriter.WriteLine(DateTime.Now + "|SYSLOG|=>$ " + "Connected");

                byte[] array = new byte[4];
                pipeClient.Read(array, 0, 4);
                var lenght = BitConverter.ToInt32(array, 0);
                logWriter.WriteLine(DateTime.Now + "|LOGED_DATA|=>$ " + "Data(Lenght):" + lenght);
                byte[] PeArray = new byte[lenght];
                pipeClient.Read(PeArray, 0, lenght);
                logWriter.WriteLine(DateTime.Now + "|LOGED_DATA|=>$ " + "Readed");

                var assembly  = Assembly.Load(PeArray);
                var instance  = assembly.CreateInstance("onfly.TestClass");
                var resultOut = assembly.GetType("onfly.TestClass").GetMethod("CodeCompile").Invoke(instance, null).ToString();

                logWriter.WriteLine(DateTime.Now + "|Result|=>$ " + "\n\t{" + resultOut + "\n\t}");


                Console.Error.WriteLine(resultOut);



                pipeClient.Close();
                pipeClient.Dispose();
                logWriter.WriteLine(DateTime.Now + "|SYSLOG|=>$" + "Disconected");
                logWriter.Flush();
                logWriter.Close();
                logWriter.Dispose();
            }
            catch (Exception ex)
            {
                logWriter.WriteLine(DateTime.Now + "|Exception|=>$ " + ex);
                logWriter.Flush();
                logWriter.Close();
                logWriter.Dispose();
            }
            Thread.Sleep(1000);
            return(0);
        }
Exemplo n.º 6
0
        private void pipeStreamer()
        {
again:
            using (var pipe = new NamedPipeClientStream(
                       ".", "antiv1",
                       PipeDirection.InOut,
                       PipeOptions.None))
            {
                byte[] buf;
                while (!closing)
                {
                    if (!pipe.IsConnected)
                    {
                        pipe.Connect();
                        buf = new byte[] { 0, 11 };
                        pipe.Write(buf, 0, buf.Length);
                    }
                    buf = new byte[128];
                    pipe.Read(buf, 0, buf.Length);
                    if (buf[1] != 0)
                    {
                        lock (messageIn)
                            messageIn.Enqueue(
                                Encoding.UTF8.GetString(buf, 0, buf.Length));
                    }
                    lock (messageOut)
                    {
                        if (messageOut.Count > 0)
                        {
                            buf = Encoding.UTF8.GetBytes(messageOut.Dequeue());
                        }
                        else
                        {
                            buf = new byte[] { 0, 0 }
                        };
                    }
                    try
                    {
                        pipe.Write(buf, 0, buf.Length);
                    }
                    catch (Exception ex) { goto again; }
                }
                buf = new byte[256];
                pipe.Read(buf, 0, buf.Length);
                lock (messageIn)
                    messageIn.Enqueue(
                        Encoding.UTF8.GetString(buf, 0, buf.Length));
                buf = new byte[] { 0, 1 };
                pipe.Write(buf, 0, buf.Length);
                pipe.WaitForPipeDrain();
            }
        }
Exemplo n.º 7
0
        public void StartEngine()
        {
            try
            {
                //启动程序
                P.Start();
                //P = Process.Start("python\\pipe.py", "\\\\.\\pipe\\" + PipeName);
                //Client.Connect(timeout*10);
                while (!Client.IsConnected)
                {
                    if (!P.HasExited)
                    {
                        try
                        {
                            Client.Connect(timeout * 10);
                        }
                        catch
                        {
                            ;
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                string s = "csharpPipe";

                result.Initialize();
                resultLength = Encoding.UTF8.GetBytes(s, 0, s.Length, result, 0);
                Client.Write(result, 0, resultLength);

                result.Initialize();
                Thread T = new Thread(() => { resultLength = Client.Read(result, 0, IOBuffSize); });
                T.Start();
                T.Join(timeout);
                s = Encoding.UTF8.GetString(result, 0, resultLength);

                if (s != "pythonPipe")
                {
                    throw new Exception("Connection Failed");
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Issue a command to the LRPC2 endpoint and receive the reply
        /// </summary>
        /// <param name="command">Command/Message Id</param>
        /// <param name="payload">Parameters</param>
        /// <returns></returns>
        public IEnumerable <object> SendCommandAndGetReply(UInt16 command, params object[] payload)
        {
            uint randomSequenceNumber = (uint)m_random.Next();

            //Encode payload
            LRPC2Data data = new LRPC2Data();

            data.Command = command;
            data.Payload = payload;
            byte[] encodedData = data.EncodeData();
            if (encodedData.Length > m_maxMessageSize)
            {
                throw new ApplicationException(string.Format("LRPC2 message payload size ({0}) exceeds the maximum message size allowed ({1})", encodedData.Length, m_maxMessageSize));
            }

            //Encode header
            LRPC2Header header = new LRPC2Header((ulong)Process.GetCurrentProcess().Id, randomSequenceNumber, (ulong)DateTime.UtcNow.Ticks, Convert.ToUInt32(encodedData.Length));

            byte[] encodedHeader = header.GetBytes();

            //Join header and payload and write to the pipe
            byte[] completePayload = new byte[encodedHeader.Length + encodedData.Length];
            Array.Copy(encodedHeader, 0, completePayload, 0, encodedHeader.Length);
            Array.Copy(encodedData, 0, completePayload, encodedHeader.Length, encodedData.Length);
            m_pipeClient.Write(completePayload, 0, completePayload.Length);

            //Read response
            byte[] responseHeaderBytes = new byte[LRPC2Constants.HEADER_LENGTH];
            m_pipeClient.Read(responseHeaderBytes, 0, LRPC2Constants.HEADER_LENGTH);
            header = new LRPC2Header(responseHeaderBytes);
            if (header.SequenceNumber == randomSequenceNumber)
            {
                byte[] responseMessageBytes = new byte[header.MessageDataLength];
                m_pipeClient.Read(responseMessageBytes, 0, (int)header.MessageDataLength);
                using (MemoryStream ms = new MemoryStream(responseMessageBytes))
                {
                    using (BinaryReader br = new BinaryReader(ms))
                    {
                        data = new LRPC2Data(br);
                        return(data.Payload);
                    }
                }
            }
            else
            {
                throw new ApplicationException(string.Format("Response header contained incorrect sequence number ({0}). Expected ({1})", header.SequenceNumber, randomSequenceNumber));
            }
        }
Exemplo n.º 9
0
    public static void ServerSendsByteClientReceives()
    {
        using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.Out))
        {
            byte[] sent     = new byte[] { 123 };
            byte[] received = new byte[] { 0 };
            Task   t        = Task.Run(() =>
            {
                using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foo", PipeDirection.In))
                {
                    client.Connect();
                    Assert.True(client.IsConnected);

                    int bytesReceived = client.Read(received, 0, 1);
                    Assert.Equal(1, bytesReceived);
                }
            });
            server.WaitForConnection();
            Assert.True(server.IsConnected);

            server.Write(sent, 0, 1);

            t.Wait();
            Assert.Equal(sent[0], received[0]);
        }
    }
Exemplo n.º 10
0
 public byte[] Read(byte[] rb)
 {
     rw_semaphore.WaitOne();
     if (exit_app)
     {
         rw_semaphore.Release();
         return(null);
     }
     else if (cli_pipe == null)
     {
         Open(false);
     }
     //else if (mq == null) OpenMessageQueue();
     try
     {
         cli_pipe.Read(rb, 0, rb.Length);
         //Message msg = mq.Receive(TimeSpan.FromSeconds(2), MessageQueueTransactionType.Automatic);
         //byte[] rst = (byte[])msg.Body;
         return(rb);
     }catch (MessageQueueException mqe)
     {
         Console.WriteLine(mqe.ToString());
         return(null);
     }
     finally
     {
         rw_semaphore.Release();
     }
 }
Exemplo n.º 11
0
 private D3Header SendD3Cmd(D3Header SendBuffer)
 {
     Thread.Sleep(5); // damit CPU nicht ausgelastet wird.
     lock (this)
     {
         object bufferOBJ  = (object)SendBuffer;
         byte[] ByteStruct = new byte[Marshal.SizeOf(SendBuffer)];
         IntPtr ptr        = Marshal.AllocHGlobal(Marshal.SizeOf(SendBuffer));
         Marshal.StructureToPtr(SendBuffer, ptr, true);
         Marshal.Copy(ptr, ByteStruct, 0, Marshal.SizeOf(SendBuffer));
         Marshal.FreeHGlobal(ptr);
         NamedPipeClientStream pipeClient;
         SendBuffer.returnValue1.i = -1;
         SendBuffer.returnValue2.i = -1;
         SendBuffer.returnValue1.f = -1;
         SendBuffer.returnValue2.f = -1;
         try
         {
             pipeClient = new NamedPipeClientStream(".", "D3_" + this.D3Process.Id, PipeDirection.InOut);
             pipeClient.Connect(1000);
             if (pipeClient.IsConnected)
             {
                 pipeClient.Write(ByteStruct, 0, Marshal.SizeOf(SendBuffer));
                 pipeClient.Read(ByteStruct, 0, Marshal.SizeOf(SendBuffer));
             }
             IntPtr i = Marshal.AllocHGlobal(Marshal.SizeOf(bufferOBJ));
             Marshal.Copy(ByteStruct, 0, i, Marshal.SizeOf(bufferOBJ));
             bufferOBJ = Marshal.PtrToStructure(i, bufferOBJ.GetType());
             Marshal.FreeHGlobal(i);
             pipeClient.Close();
         }
         catch { }
         return((D3Header)bufferOBJ);
     }
 }
Exemplo n.º 12
0
        private void _Reader()
        {
            _pipe.Connect();

            // read data from pipe
            while (_pipe.IsConnected && _pipe.CanRead)
            {
                var buffer    = new byte[4096];
                var bytesRead = _pipe.Read(buffer, 0, buffer.Length);

                if (bytesRead > 0)
                {
                    // create message data block
                    var messageData = buffer.Take(bytesRead);

                    // append message data
                    _buffer.Append(messageData);

                    // parse message
                    _parseData();
                }

                Thread.Sleep(50); // wait to data availability
            }
        }
Exemplo n.º 13
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);
            }
        }
Exemplo n.º 14
0
        private static void StartClientBytes()
        {
            NamedPipeClientStream pipeClient =
                new NamedPipeClientStream(".", "testpipe",
                                          PipeDirection.InOut, PipeOptions.None,
                                          TokenImpersonationLevel.Impersonation);

            pipeClient.Connect();
            pipeClient.ReadMode = PipeTransmissionMode.Message;


            while (pipeClient.IsConnected)
            {
                Console.Write("Ready: ");
                string readline = Console.ReadLine();


                byte[] resp = UnicodeEncoding.Default.GetBytes(readline);

                pipeClient.Write(resp, 0, resp.Length);


                StringBuilder sb = new StringBuilder();

                do
                {
                    var buffer    = new byte[10];
                    var readBytes = pipeClient.Read(buffer, 0, buffer.Length);
                    sb.Append(UnicodeEncoding.Default.GetString(buffer));
                }while (!pipeClient.IsMessageComplete);

                Console.WriteLine(sb.ToString().TrimEnd('\0'));
            }
            pipeClient.Close();
        }
Exemplo n.º 15
0
 public string SendMessage(string message)
 {
     try
     {
         byte[] buffer = Encoding.UTF8.GetBytes(message);
         if (!ClientStream.IsConnected)
         {
             return("Клиент не подключился к серверу");
         }
         ClientStream.Write(buffer, 0, buffer.Length);
         ClientStream.Flush();
         const int maxResponseSize = 1024;
         buffer = new byte[maxResponseSize];
         int    responseSize = ClientStream.Read(buffer, 0, maxResponseSize);
         string response     = Encoding.UTF8.GetString(buffer, 0, responseSize);
         if (response != "OK")
         {
             return("Неизвестная ошибка на сервере");
         }
         return(null);
     }
     catch (System.IO.IOException)
     {
         return("Сервер не отвечает");
     }
 }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            var config                = HostConfig.GetHostConfig();
            var nativeModules         = GetNativeModules(config);
            var managedModules        = GetManagedModule(config);
            HttpNativeRuntime runtime = null;

            try
            {
                int  workerProcessId = Process.GetCurrentProcess().Id;
                ILog log             = LogManager.GetLogger("WorkerProcess");
                using (NamedPipeClientStream pipeStream = new NamedPipeClientStream($"{workerProcessId}.Request"))
                {
                    Byte[] bytes = new Byte[10];
                    Char[] chars = new Char[10];

                    using (NamedPipeServerStream responsePipeStream = new NamedPipeServerStream($"{workerProcessId}.Response",
                                                                                                PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.None))
                    {
                        while (true)
                        {
                            string message = null;
                            if (!pipeStream.IsConnected)
                            {
                                pipeStream.Connect();
                                pipeStream.ReadMode = PipeTransmissionMode.Message;
                            }
                            do
                            {
                                int numBytes = pipeStream.Read(bytes, 0, bytes.Length);
                                int numChars = Encoding.UTF8.GetChars(bytes, 0, numBytes, chars, 0);
                                if (numBytes > 0)
                                {
                                    message += new String(chars, 0, numChars);
                                }
                            } while (!pipeStream.IsMessageComplete);

                            if (!string.IsNullOrEmpty(message))
                            {
                                if (runtime == null)
                                {
                                    runtime = new HttpNativeRuntime(nativeModules, managedModules);
                                    var site = config.GetRequestingSite(message);
                                    runtime.PhysicalPath = site.PhysicalPath;
                                }
                                responsePipeStream.WaitForConnection();
                                var data = runtime.ProcessRequest(message);
                                responsePipeStream.Write(data, 0, data.Length);
                                responsePipeStream.Disconnect();
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.Write(e);
                Console.Read();
            }
        }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            var pipename   = "pipey";
            var pipeClient = new NamedPipeClientStream(pipename);

            Console.WriteLine("Connecting to server pipe '{0}'", pipename);
            pipeClient.Connect();
            var hdr     = new PipeHeader();
            var hdrSize = Marshal.SizeOf(hdr);

            hdr.command  = 1;
            hdr.sockid   = 1912;
            hdr.datasize = 32;
            var buf = Serialize(hdr);

            Console.WriteLine("Writing to server pipe");
            pipeClient.Write(buf, 0, hdrSize);
            pipeClient.Read(buf, 0, hdrSize);
            hdr = (PipeHeader)Deserialize(buf, hdr.GetType());
            Console.WriteLine("Pipe read {{ command: {0}, sockid: {1}, datasize: {2} }}",
                              hdr.command, hdr.sockid, hdr.datasize);
            hdr.command = 0;     // tell server to disconnect
            buf         = Serialize(hdr);
            Console.WriteLine("Sending disconnect");
            pipeClient.Write(buf, 0, hdrSize);
            pipeClient.Close();
            Console.WriteLine("Pipe closed");
        }
Exemplo n.º 18
0
        public void SendCommand(ApplicationCommand cmd)
        {
            if (mClient == null)
            {
                CommandEventArgs args = new CommandEventArgs()
                {
                    Command = cmd
                };
                DispatchCommand(args);
                HandleResponse(args.Handle);
                return;
            }
            try
            {
                string text   = JsonConvert.SerializeObject(cmd);
                byte[] bytes  = Encoding.UTF8.GetBytes(text);
                byte[] count  = BitConverter.GetBytes(bytes.Length);
                byte[] handle = new byte[Marshal.SizeOf(typeof(long))];
                mClient.Write(count, 0, count.Length);
                mClient.Write(bytes, 0, bytes.Length);
                mClient.Read(handle, 0, handle.Length);

                IntPtr hwnd = (IntPtr)BitConverter.ToInt64(handle, 0);
                HandleResponse(hwnd);
            }
            catch (IOException)
            {
            }
            mClient.Dispose();
            mClient = null;
        }
Exemplo n.º 19
0
        /// <summary>
        /// Reades a byte array from the inbound pipe using one or more packages.
        /// </summary>
        /// <returns>The byte array that is read.</returns>
        protected void Read(out Byte[] data)
        {
            _log.Debug(nameof(Read));

            Byte[] buffer    = new Byte[sizeof(Int32)];
            Int32  byteCount = _inStream.Read(buffer, 0, buffer.Length);

            _log.Debug($"Read {byteCount.Format()} out of expected {buffer.Length.Format()} Bytes.");

            Int32 length = BitConverter.ToInt32(buffer, 0);

            _log.Debug($"Length is {length.Format()}.");

            using (MemoryStream ms = new MemoryStream()) {
                for (Int32 i = 0; i < length; i += UInt16.MaxValue)
                {
                    buffer    = new Byte[Math.Min(length - i, UInt16.MaxValue)];
                    byteCount = _inReader.Read(buffer, 0, buffer.Length);

                    _log.Debug($"Read {byteCount.Format()} out of expected {buffer.Length.Format()} Bytes.");

                    ms.Write(buffer, 0, buffer.Length);
                }

                data = ms.ToArray();
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Метод с кодом для потока получателя информации с канала
        /// </summary>
        void Reader()
        {
            try
            {
                pipeClient.Connect();

                InvokeOnUI(() =>
                {
                    panelStatus.BackgroundImage = Properties.Resources.Connected;
                });
                UpdateVisibility();

                // читаем из канала в цикле, пока подключены
                while (pipeClient.IsConnected)
                {
                    var buffer = new byte[2048];
                    var length = pipeClient.Read(buffer, 0, buffer.Length);

                    var message = Encoding.UTF8.GetString(buffer, 0, length);

                    OnRecieve(message);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            InvokeOnUI(() =>
            {
                panelStatus.BackgroundImage = Properties.Resources.Disconnected;
            });
        }
Exemplo n.º 21
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();
                }
            }
        }
Exemplo n.º 22
0
        private void PipeWriteCallback(IAsyncResult ar)
        {
            var pipe = (NamedPipeClientStream)ar.AsyncState;

            pipe.EndWrite(ar);
            pipe.Flush();
            //pipe.WaitForPipeDrain();		// 阻塞



            Decoder decoder = Encoding.UTF8.GetDecoder();

            Byte[] bytes = new Byte[10];
            Char[] chars = new Char[10];

            string message = "";

            do
            {
                int numBytes = _pipe.Read(bytes, 0, bytes.Length);
                int numChars = decoder.GetChars(bytes, 0, numBytes, chars, 0);
                message += new String(chars, 0, numChars);
            } while (!_pipe.IsMessageComplete);
            Console.WriteLine(message);
            decoder.Reset();
        }
Exemplo n.º 23
0
        public static void GetState()
        {
            NamedPipeClientStream client = new NamedPipeClientStream("localhost", XConfig.Current.StatusReportNamedPipe, PipeDirection.In);

            while (true)
            {
                client.Connect();
                while (client.IsConnected)
                {
                    var data = new byte[65535];
                    try
                    {
                        var count = client.Read(data, 0, data.Length);
                        if (count > 0)
                        {
                            HomeController.ServerStatus = JsonConvert.DeserializeObject <StatusReportObject>(Encoding.UTF8.GetString(data, 0, count));
                        }
                    }
                    catch (Exception ex)
                    {
                        ex.LogException();
                    }
                    finally
                    {
                        GC.Collect();
                    }
                }
                L.E("DisConnected from the WBWebServer....");
                Thread.Sleep(1000);
            }
        }
Exemplo n.º 24
0
 private void CreateClient()
 {
     using (pipeClient = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut))
     {
         try
         {
             Logger.Info("Client connecting PipeName:" + pipeName);
             pipeClient.Connect(timeOut);
             Logger.Info("Client is connected PipeName:" + pipeName);
             this.isConnected = true;
             while (true)
             {
                 Thread.Sleep(1);
                 byte[] data   = new byte[PipeBufferSize];
                 int    read   = pipeClient.Read(data, 0, data.Length);
                 string resMsg = Encoding.UTF8.GetString(data, 0, read);
                 pipeClient.FlushAsync();
                 Logger.Info("Get Message:" + resMsg);
                 if (string.IsNullOrEmpty(resMsg))
                 {
                     break;
                 }
                 this.MessageReceived?.Invoke(resMsg);
             }
         }
         catch (Exception ex)
         {
             Logger.Error("CreateClient err:" + ex.Message);
             this.isConnected = false;
         }
     }
     Logger.Info("Client is disconnected:" + pipeName);
     Thread.Sleep(1);
     CreateClient();
 }
Exemplo n.º 25
0
        public async Task ReadFromPipeAsync(CancellationToken token)
        {
            await _namedPipe.ConnectAsync(token);

            while (true)
            {
                token.ThrowIfCancellationRequested();
                int readBytes = _namedPipe.Read(_pipeWriter.GetSpan());
                if (readBytes == 0)
                {
                    await Task.Delay(500, token);

                    continue;
                }

                _pipeWriter.Advance(readBytes);

                FlushResult result = await _pipeWriter.FlushAsync(token);

                if (result.IsCanceled)
                {
                    break;
                }
            }
            _pipeWriter.Complete();
        }
Exemplo n.º 26
0
        public string Read(NamedPipeClientStream client)
        {
            var buffer = new byte[1000];

            client.Read(buffer, 0, 1000);
            return(GetString(buffer));
        }
Exemplo n.º 27
0
        static void Main()
        {
            try
            {
                using (var pipe = new NamedPipeClientStream(".", "sharp-express", PipeDirection.InOut))
                {
                    pipe.Connect();

                    var encoding = Encoding.UTF8;
                    var sb       = new StringBuilder();
                    sb.Append("GET / HTTP/1.1\r\n");
                    sb.Append("Header1: Hi!\r\n");
                    sb.Append("\r\n");

                    var bytes = encoding.GetBytes(sb.ToString());
                    pipe.Write(bytes, 0, bytes.Length);
                    pipe.Flush();

                    var buf     = new byte[64 * 1024];
                    var size    = pipe.Read(buf, 0, buf.Length);
                    var message = encoding.GetString(buf, 0, size);
                    Console.WriteLine(message);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Console.ReadLine();
        }
Exemplo n.º 28
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="args"></param>
 static void Main(string[] args)
 {
     Console.Title = "命名管道-客户端";
     using (NamedPipeClientStream namedClientStream = new NamedPipeClientStream("localhost", NAMED_PIPE_SERVER))
     {
         Console.WriteLine("正在连接...");
         try
         {
             namedClientStream.Connect(30000);
             Console.WriteLine("成功连接至{0}", NAMED_PIPE_SERVER);
             while (namedClientStream.CanRead)
             {
                 byte[] buffer = new byte[78];
                 namedClientStream.Read(buffer, 0, buffer.Length);
                 string strReciveData = System.Text.Encoding.UTF8.GetString(buffer);
                 Console.WriteLine("接收到消息!{0}", strReciveData);
                 System.Threading.Thread.Sleep(1000);
             }
         }
         catch (System.IO.IOException ex)
         {
             Console.WriteLine(ex.Message);
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.Message);
         }
     }
     Console.ReadLine();
 }
Exemplo n.º 29
0
        /// <summary>
        /// IIS document does not specify how w3svc send request to worker process, so here we use named pipeline to send message
        /// In real iis I assume they must be using windows api to do this
        /// </summary>
        /// <param name="request"></param>
        /// <param name="workerProcess"></param>
        /// <param name="appPoolName"></param>
        /// <param name="responseHandler"></param>
        private static void SendRequestToWorkerProcess(string request, Process workerProcess, Action <string> responseHandler)
        {
            using (NamedPipeServerStream pipeStream = new NamedPipeServerStream($"{workerProcess.Id.ToString()}.Request",
                                                                                PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.None))
            {
                if (!pipeStream.IsConnected)
                {
                    pipeStream.WaitForConnection();
                }
                var data = Encoding.UTF8.GetBytes(request);
                pipeStream.Write(data, 0, data.Length);
            }

            Byte[] bytes = new Byte[10];
            Char[] chars = new Char[10];
            using (NamedPipeClientStream pipeStream = new NamedPipeClientStream($"{workerProcess.Id.ToString()}.Response"))
            {
                string message = string.Empty;
                pipeStream.Connect();
                pipeStream.ReadMode = PipeTransmissionMode.Message;
                do
                {
                    int numBytes = pipeStream.Read(bytes, 0, bytes.Length);
                    int numChars = Encoding.UTF8.GetChars(bytes, 0, numBytes, chars, 0);
                    message += new String(chars, 0, numChars);
                } while (!pipeStream.IsMessageComplete);
                responseHandler(message);
            }
        }
Exemplo n.º 30
0
        public CClashResponse Transact(CClashRequest req)
        {
            Connect();
            CClashResponse resp = null;

            req.pid = System.Diagnostics.Process.GetCurrentProcess().Id;
            var txbuf = req.Serialize();

            ncs.Write(txbuf, 0, txbuf.Length);
            ncs.Flush();

            var rx = new List <byte>();

            var rxbuf = new byte[8192];

            do
            {
                var rbytes = ncs.Read(rxbuf, 0, rxbuf.Length);
                rx.AddRange(rxbuf.Take(rbytes));
            } while (!ncs.IsMessageComplete);

            if (rx.Count > 0)
            {
                resp = CClashMessage.Deserialize <CClashResponse>(rx.ToArray());
                ncs.Close();
            }
            return(resp);
        }
Exemplo n.º 31
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();
                }
            }

        }