/// <summary>
        /// Calls method with one parameter and result. Deserializes parameter and serialize result.
        /// </summary>
        /// <param name="type">Type containing method</param>
        /// <param name="methodName">Name of method to call</param>
        /// <param name="pipeName">Name of pipe to pass parameter and result</param>
        static void InvokeFunc(Type type, string methodName, string pipeName)
        {
            using (var pipe = new NamedPipeClientStream(pipeName))
            {

                pipe.Connect();

                var formatter = new BinaryFormatter();
                ProcessThreadParams pars;
                var lengthBytes = new byte[4];
                pipe.Read(lengthBytes, 0, 4);
                var length = BitConverter.ToInt32(lengthBytes, 0);

                var inmemory = new MemoryStream(length);
                var buf = new byte[1024];
                while (length != 0)
                {
                    var red = pipe.Read(buf, 0, buf.Length);
                    inmemory.Write(buf, 0, red);
                    length -= red;
                }
                inmemory.Position = 0;
                try
                {
                    AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
                      {
                          return type.Assembly;
                      };

                    pars = (ProcessThreadParams)formatter.Deserialize(inmemory);

                    var method = type.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, null, pars.Types, null);
                    if (method == null) throw new InvalidOperationException("Method is not found: " + methodName);

                    if (pars.Pipe != null)
                    {
                        var auxPipe = new NamedPipeClientStream(pars.Pipe);
                        auxPipe.Connect();

                        for (int i = 0; i < pars.Parameters.Length; i++)
                            if (pars.Parameters[i] is PipeParameter) pars.Parameters[i] = auxPipe;
                    }
                    object result = method.Invoke(pars.Target, pars.Parameters);

                    var outmemory = new MemoryStream();
                    formatter.Serialize(outmemory, ProcessThreadResult.Successeded(result));
                    outmemory.WriteTo(pipe);
                }
                catch (TargetInvocationException e)
                {
                    formatter.Serialize(pipe, ProcessThreadResult.Exception(e.InnerException));
                    throw e.InnerException;
                }
                catch (Exception e)
                {
                    formatter.Serialize(pipe, ProcessThreadResult.Exception(e));
                    throw;
                }
            }
        }
Пример #2
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();
        }
Пример #3
0
        static void Main()
        {
            try {
                using (var npcs = new NamedPipeClientStream("Stream Mosaic")) {
                    try {
                        npcs.Connect(500);

                        var url = Environment.CommandLine.Substring(Environment.CommandLine.IndexOf(' ')).Trim();

                        var textBytes = Encoding.UTF8.GetBytes(url);
                        npcs.Write(textBytes, 0, textBytes.Length);
                        npcs.Flush();

                        var responseBytes = new byte[1];
                        npcs.Read(responseBytes, 0, 1);
                    } catch (TimeoutException) {
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Application.Run(new MainWindow());
                    }
                }
            } catch (Exception exc) {
                MessageBox.Show(exc.ToString());
            }
        }
Пример #4
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]);
        }
    }
Пример #5
0
        public void Run()
        {
            while (true)
            {
                using (pipeClient = new NamedPipeClientStream(
                    "localhost",
                    Config.PipeName,
                    PipeDirection.InOut,
                    PipeOptions.None
                    ))
                {

                    try
                    {
                        Console.Write("Waiting for new connection...");
                        pipeClient.Connect(5000);
                        Console.WriteLine("...Connected!");
                        pipeClient.ReadMode = PipeTransmissionMode.Message;

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("...timed out :(");
                    }

                    try
                    {
                        while (pipeClient.IsConnected)
                        {

                            byte[] bResponse = new byte[Config.BufferSize];
                            int cbResponse = bResponse.Length;

                            int cbRead = pipeClient.Read(bResponse, 0, cbResponse);

                            var message = Encoding.Unicode.GetString(bResponse).TrimEnd('\0');
                            Console.WriteLine(message);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error: " + ex.Message);
                    }
                    finally
                    {
                        Console.WriteLine("Connection lost");
                        if (pipeClient != null)
                        {
                            Console.WriteLine("Cleaning up pipe connection...");
                            pipeClient.Close();
                            pipeClient = null;
                        }
                    }
                }
            }
        }
Пример #6
0
        static void Main(string[] args)
        {
            string[] simpleNames = { "Yukari", "Maki", "Zunko", "Akane", "Aoi", "Koh" };
            string[] simpleNamesA = { "yukari", "maki", "zunko", "akane", "aoi", "koh" };

            //引数のチェック
            if (args.Length < 2) {
                string mergeName = "";
                for (int i = 0; i < simpleNames.Length; i++)
                {
                    mergeName = mergeName + simpleNames[i];
                    //ワード間に", "をつける
                    if (i < simpleNames.Length - 1)
                        mergeName = mergeName + ", ";
                }
                Console.WriteLine("引数を指定してください: VoiceroidTClient"+ mergeName +" [会話内容];[音量0.0-2.0];[話速0.5-4.0];[高さ0.5-2.0];[抑揚0.0-2.0]");
                return;
            }
            //引数に設定されたボイスロイドの名前をチェック
            string selectedSimple = null;
            for (int i = 0; i < simpleNames.Length; i++) {
                if (args[0].CompareTo(simpleNames[i]) == 0 || args[0].CompareTo(simpleNamesA[i]) == 0) {
                    selectedSimple = simpleNames[i];
                }
            }
            if (selectedSimple == null) {
                string mergeName = "";
                for (int i = 0; i < simpleNames.Length; i++)
                {
                    mergeName = mergeName + simpleNames[i];
                    //ワード間に", "をつける
                    if (i < simpleNames.Length - 1)
                        mergeName = mergeName + ", ";
                }
                Console.WriteLine("第一引数に指定されたVOICEROIDの名前が正しくありません. 使用できる名前は次のとおりです: "+ mergeName);
                return;
            }
            //サーバーとの通信処理を開始
            string message = args[1];
            try {
                //サーバーのセッションを取得する
                using (NamedPipeClientStream client = new NamedPipeClientStream("voiceroid_talker" + selectedSimple)) {
                        client.Connect(1000);
                    //サーバにーメッセージを送信する
                    byte[] buffer = UnicodeEncoding.Unicode.GetBytes(message);
                    client.Write(buffer, 0, buffer.Length);
                    byte[] response = new byte[4];
                    client.Read(response, 0, response.Length);
                    client.Close();
                }
            } catch (Exception e) {
                //サーバーに接続できない時、通信エラーが発生した場合
                Console.WriteLine("VoiceroidTServerによるサーバー, [voiceroid_talker" + selectedSimple + "]が見つかりません.");
            }
        }
Пример #7
0
        private void SendCommand(int pid, string command)
        {
            var clientStream = new NamedPipeClientStream(".", this.PipeNameForPid(pid), 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());
        }
Пример #8
0
        private static byte[] ReadCommandFromEnviroGen(NamedPipeClientStream pipe)
        {
            //We read into this buffer because this will block until we get a byte,
            //which is what we want in this case.
            var commandRead = new byte[1];
            pipe.Read(commandRead, 0, 1);

            Console.WriteLine($"Raw command read: {commandRead[0]}");

            var commandLength = ServerCommands.CommandLengths[commandRead[0]];
            var input = new byte[1 + commandLength];

            input[0] = commandRead[0];

            if (commandLength > 0)
            {
                //TODO: handle improper number of bytes sent, currently this just blocks if the amount is too low
                //Read all the command args into the input array
                pipe.Read(input, 1, commandLength);
            }

            return input;
        }
Пример #9
0
        private void Form1_Load(object sender, EventArgs e)
        {
            _spyMgr.LoadCustomDll(_process, @"..\..\..\Plugin\bin\Plugins\CRegistryPlugin.dll", false, false);

            pipe = new NamedPipeClientStream(".", "HyperPipe32", PipeDirection.InOut);
            pipe.Connect();

            byte[] data = new byte[4];
            pipe.Read(data, 0, 4);
            Int32 address = BitConverter.ToInt32(data, 0);

            NktHook hook = _spyMgr.CreateHookForAddress((IntPtr)address, "D3D9.DLL!CreateDevice", (int)(eNktHookFlags.flgRestrictAutoHookToSameExecutable | eNktHookFlags.flgOnlyPostCall | eNktHookFlags.flgDontCheckAddress));
            hook.AddCustomHandler(@"..\..\..\Plugin\bin\Plugins\CRegistryPlugin.dll", 0, "");

            hook.Attach(_process, true);
            hook.Hook(true);

            _spyMgr.ResumeProcess(_process, continueevent);
        }
Пример #10
0
        private static void ChunkRequestSpeedTest(object data)
        {
            //initialize world
            SendCommandToEnviroGen(new byte[] { 1, 10, 10});

            var getChunkCommand = new byte[] { 4, 0, 0 };

            m_Watch.Start();
            for (var i = 0; i < 1000; i++)
            {
                var pipe = new NamedPipeClientStream(".", m_OutputPipeName, PipeDirection.InOut);
                pipe.Connect();
                pipe.Write(getChunkCommand, 0, getChunkCommand.Length);
                var input = new byte[32768 + 1];
                pipe.Read(input, 0, input.Length);
            }
            m_Watch.Stop();
            Console.WriteLine($"EnviroGen took {m_Watch.ElapsedMilliseconds}ms to serve 1000 chunks.");
            Console.WriteLine($"Average Time: {m_Watch.ElapsedMilliseconds / 1000f}ms");
            m_Watch.Reset();

            Console.ReadLine();
        }
Пример #11
0
 private D3Header SendD3Cmd()
 {
     Thread.Sleep(10); // damit CPU nicht ausgelastet wird. so CPU is not busy.
     lock (this)
     {
         object bufferOBJ = (object)this.D3Mail;
         if (this.D3Process != null)
         {
             byte[] ByteStruct = new byte[Marshal.SizeOf(this.D3Mail)];
             IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(this.D3Mail));
             Marshal.StructureToPtr(this.D3Mail, ptr, true);
             Marshal.Copy(ptr, ByteStruct, 0, Marshal.SizeOf(this.D3Mail));
             Marshal.FreeHGlobal(ptr);
             NamedPipeClientStream pipeClient;
             pipeClient = new NamedPipeClientStream(".", "D3_" + this.D3Process.Id, PipeDirection.InOut);
             try
             {
                 pipeClient.Connect(200);
                 if (pipeClient.IsConnected)
                 {
                     pipeClient.Write(ByteStruct, 0, Marshal.SizeOf(this.D3Mail));
                     pipeClient.Read(ByteStruct, 0, Marshal.SizeOf(this.D3Mail));
                 }
                 IntPtr i = Marshal.AllocHGlobal(Marshal.SizeOf(bufferOBJ));
                 Marshal.Copy(ByteStruct, 0, i, Marshal.SizeOf(bufferOBJ));
                 bufferOBJ = Marshal.PtrToStructure(i, bufferOBJ.GetType());
                 Marshal.FreeHGlobal(i);
             }
             catch (Exception e) { _logger.Log("[IPlugin] D3 Command Exception." + e); }
             finally
             {
                 pipeClient.Close();
             }
         }
         return this.D3Mail = (D3Header)bufferOBJ;
     }
 }
Пример #12
0
        private void QvxCommandWorker()
        {
            try
            {
                if (pipeName == null) return;

                object state = new object();
                object connection = null;

                using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut))
                {
                    var buf = new byte[4];
                    var buf2 = new byte[4];
                    Int32 count = 0;
                    Int32 datalength = 0;
                    pipeClient.Connect(1000);
                    while (pipeClient.IsConnected)
                    {
                        try
                        {
                            #region Get QvxRequest
                            var iar = pipeClient.BeginRead(buf, 0, 4, null, state);
                            while (!iar.IsCompleted) Thread.Sleep(1);
                            count = pipeClient.EndRead(iar);
                            if (count != 4) throw new Exception("Invalid Count Length");
                            buf2[0] = buf[3];
                            buf2[1] = buf[2];
                            buf2[2] = buf[1];
                            buf2[3] = buf[0];
                            datalength = BitConverter.ToInt32(buf2, 0);
                            var data = new byte[datalength];
                            count = pipeClient.Read(data, 0, datalength);
                            if (count != datalength) throw new Exception("Invalid Data Length");

                            var sdata = ASCIIEncoding.ASCII.GetString(data);
                            sdata = sdata.Replace("\0", "");
                            QvxRequest request;
                            try
                            {
                                request = QvxRequest.Deserialize(sdata);

                            }
                            catch (Exception ex)
                            {
                                logger.Error(ex);
                                throw ex;
                            }
                            request.QVWindow = QVWindow;
                            request.Connection = connection;
                            #endregion

                            #region Handle QvxRequets
                            QvxReply result = null;
                            if (HandleQvxRequest != null)
                                result = HandleQvxRequest(request);

                            if (result == null)
                                result = new QvxReply() { Result = QvxResult.QVX_UNKNOWN_ERROR };
                            #endregion

                            #region Send QvxReply
                            sdata = "    " + result.Serialize() + "\0";
                            datalength = sdata.Length - 4;
                            buf2 = ASCIIEncoding.ASCII.GetBytes(sdata);
                            buf = BitConverter.GetBytes(datalength);
                            buf2[0] = buf[3];
                            buf2[1] = buf[2];
                            buf2[2] = buf[1];
                            buf2[3] = buf[0];
                            pipeClient.Write(buf2, 0, buf2.Length);
                            pipeClient.WaitForPipeDrain();
                            #endregion

                            #region Handle result States
                            if (result.Terminate)
                                close = true;
                            if (result.Connection != null)
                                connection = result.Connection;
                            if (result.SetConnectionNULL)
                                connection = null;
                            #endregion
                        }
                        catch (Exception ex)
                        {
                            logger.Error(ex);
                            Thread.Sleep(500);
                            close = true;
                        }

                        if (close)
                        {
                            close = false;
                            pipeClient.Close();
                        }

                        Thread.Sleep(5);
                    }
                }
                running = false;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
Пример #13
0
    public static async Task ClientPInvokeChecks()
    {
        using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.None, 4096, 4096))
        {
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foo", PipeDirection.Out))
            {
                Task serverTask = DoServerOperationsAsync(server);
                client.Connect();

                Assert.False(client.CanRead);
                Assert.False(client.CanSeek);
                Assert.False(client.CanTimeout);
                Assert.True(client.CanWrite);
                Assert.False(client.IsAsync);
                Assert.True(client.IsConnected);
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    Assert.Equal(0, client.OutBufferSize);
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    Assert.True(client.OutBufferSize > 0);
                }
                else
                {
                    Assert.Throws<PlatformNotSupportedException>(() => client.OutBufferSize);
                }
                Assert.Equal(PipeTransmissionMode.Byte, client.ReadMode);
                Assert.NotNull(client.SafePipeHandle);
                Assert.Equal(PipeTransmissionMode.Byte, client.TransmissionMode);

                client.Write(new byte[] { 123 }, 0, 1);
                await client.WriteAsync(new byte[] { 124 }, 0, 1);
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    client.WaitForPipeDrain();
                }
                else
                {
                    Assert.Throws<PlatformNotSupportedException>(() => client.WaitForPipeDrain());
                }
                client.Flush();

                await serverTask;
            }
        }

        using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.Out))
        {
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foo", PipeDirection.In))
            {
                Task serverTask = DoServerOperationsAsync(server);
                client.Connect();

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    Assert.Equal(0, client.InBufferSize);
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    Assert.True(client.InBufferSize > 0);
                }
                else
                {
                    Assert.Throws<PlatformNotSupportedException>(() => client.InBufferSize);
                }
                byte[] readData = new byte[] { 0, 1 };
                Assert.Equal(1, client.Read(readData, 0, 1));
                Assert.Equal(1, client.ReadAsync(readData, 1, 1).Result);
                Assert.Equal(123, readData[0]);
                Assert.Equal(124, readData[1]);

                await serverTask;
            }
        }
    }
Пример #14
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;

            }
        }
Пример #15
0
    public static void ClientPInvokeChecks()
    {
        using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.In))
        {
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foo", PipeDirection.Out))
            {
                Task serverTask = DoServerOperationsAsync(server);
                client.Connect();
                Console.WriteLine("client.CanRead = {0}", client.CanRead);
                Console.WriteLine("client.CanSeek = {0}", client.CanSeek);
                Console.WriteLine("client.CanTimeout = {0}", client.CanTimeout);
                Console.WriteLine("client.CanWrite = {0}", client.CanWrite);
                Console.WriteLine("client.IsAsync = {0}", client.IsAsync);
                Console.WriteLine("client.IsConnected = {0}", client.IsConnected);
                Console.WriteLine("client.OutBufferSize = {0}", client.OutBufferSize);
                Console.WriteLine("client.ReadMode = {0}", client.ReadMode);
                Console.WriteLine("client.SafePipeHandle = {0}", client.SafePipeHandle);
                Console.WriteLine("client.TransmissionMode = {0}", client.TransmissionMode);

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

                serverTask.Wait();
            }
        }

        using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.Out))
        {
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foo", PipeDirection.In))
            {
                Task serverTask = DoServerOperationsAsync(server);
                client.Connect();

                Console.WriteLine("client.InBufferSize = {0}", client.InBufferSize);
                byte[] readData = new byte[] { 0, 1 };
                client.Read(readData, 0, 1);
                client.ReadAsync(readData, 1, 1).Wait();
                Assert.Equal(123, readData[0]);
                Assert.Equal(124, readData[1]);

                serverTask.Wait();
            }
        }
    }
Пример #16
0
        private static void DrainPipe(NamedPipeClientStream pipeStream)
        {
            if (pipeStream == null || !pipeStream.IsConnected || !HasData(pipeStream))
                return;

            byte[] buffer = new byte[0x8000];

            do
            {
                if (pipeStream.Read(buffer, 0, buffer.Length) <= 0)
                    break;
            }
            while (HasData(pipeStream));
        }
        /// <summary>
        /// Copies the named pipe stream to the specified stream.
        /// </summary>
        /// <param name="pipeName">Pipe name.</param>
        /// <param name="target">Destination stream.</param>
        public static void CopyNamedPipeStream(this string pipeName, Stream target)
        {
            using (NamedPipeClientStream clientPipe = new NamedPipeClientStream(pipeName))
            {
                clientPipe.Connect();

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

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

                target.Flush();
            }
        }
Пример #18
0
    const int BUFFER_SIZE = 1024; // 1 KB

    #endregion Fields

    #region Methods

    static void BCLSystemIOPipeClient()
    {
        /////////////////////////////////////////////////////////////////////
        // Try to open a named pipe.
        //

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

        NamedPipeClientStream pipeClient = null;

        try
        {
            pipeClient = new NamedPipeClientStream(
                strServerName,              // The server name
                strPipeName,                // The unique pipe name
                PipeDirection.InOut,        // The pipe is bi-directional
                PipeOptions.None,           // No additional parameters

                //The server process cannot obtain identification information about
                //the client, and it cannot impersonate the client.
                TokenImpersonationLevel.Anonymous);

            pipeClient.Connect(60000); // set TimeOut for connection
            pipeClient.ReadMode = PipeTransmissionMode.Message;

            Console.WriteLine(@"The named pipe, \\{0}\{1}, is connected.",
                strServerName, strPipeName);

            /////////////////////////////////////////////////////////////////
            // Send a message to the pipe server and receive its response.
            //

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

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

            // Send one message to the pipe.

            // '\0' is appended in the end because the client may be a native
            // C++ program.
            strMessage = "Default request from client\0";
            bRequest = Encoding.Unicode.GetBytes(strMessage);
            cbRequestBytes = bRequest.Length;
            if (pipeClient.CanWrite)
            {
                pipeClient.Write(bRequest, 0, cbRequestBytes);
            }
            pipeClient.Flush();

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

            // Receive one message from the pipe.

            cbReplyBytes = BUFFER_SIZE;
            do
            {
                if (pipeClient.CanRead)
                {
                    cbBytesRead = pipeClient.Read(bReply, 0, cbReplyBytes);

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

        }
        catch (TimeoutException ex)
        {
            Console.WriteLine("Unable to open named pipe {0}\\{1}",
               strServerName, strPipeName);
            Console.WriteLine(ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("The client throws the error: {0}", ex.Message);
        }
        finally
        {
            /////////////////////////////////////////////////////////////////
            // Close the pipe.
            //

            if (pipeClient != null)
                pipeClient.Close();
        }
    }
Пример #19
0
        /// <summary>
        /// Use the types in the System.IO.Pipes namespace to connect to the 
        /// named pipe. This solution is recommended when you program against 
        /// .NET Framework 3.5 or any newer releases of .NET Framework.
        /// </summary>
        public static void Run()
        {
            NamedPipeClientStream pipeClient = null;

            try
            {
                // Try to open the named pipe identified by the pipe name.

                pipeClient = new NamedPipeClientStream(
                    Program.ServerName,         // The server name
                    Program.PipeName,           // The unique pipe name
                    PipeDirection.InOut,        // The pipe is duplex
                    PipeOptions.None            // No additional parameters
                    );

                pipeClient.Connect(5000);
                Console.WriteLine("The named pipe ({0}) is connected.",
                    Program.FullPipeName);

                // Set the read mode and the blocking mode of the named pipe. In
                // this sample, we set data to be read from the pipe as a stream
                // of messages. This allows a reading process to read varying-
                // length messages precisely as sent by the writing process. In
                // this mode, you should not use StreamWriter to write the pipe,
                // or use StreamReader to read the pipe. You can read more about
                // the difference from http://go.microsoft.com/?linkid=9721786.
                pipeClient.ReadMode = PipeTransmissionMode.Message;

                //
                // Send a request from client to server
                //

                string message = Program.RequestMessage;
                byte[] bRequest = Encoding.Unicode.GetBytes(message);
                int cbRequest = bRequest.Length;

                pipeClient.Write(bRequest, 0, cbRequest);

                Console.WriteLine("Send {0} bytes to server: \"{1}\"",
                    cbRequest, message.TrimEnd('\0'));

                //
                // Receive a response from server.
                //

                do
                {
                    byte[] bResponse = new byte[Program.BufferSize];
                    int cbResponse = bResponse.Length, cbRead;

                    cbRead = pipeClient.Read(bResponse, 0, cbResponse);

                    // Unicode-encode the received byte array and trim all the
                    // '\0' characters at the end.
                    message = Encoding.Unicode.GetString(bResponse).TrimEnd('\0');
                    Console.WriteLine("Receive {0} bytes from server: \"{1}\"",
                        cbRead, message);
                }
                while (!pipeClient.IsMessageComplete);

            }
            catch (Exception ex)
            {
                Console.WriteLine("The client throws the error: {0}", ex.Message);
            }
            finally
            {
                // Close the pipe.
                if (pipeClient != null)
                {
                    pipeClient.Close();
                    pipeClient = null;
                }
            }
        }
Пример #20
0
        /// <summary>クライアント生成 - Socketスレッド関数</summary>
        private void ClientNamedPipe()
        {
            // 通信シーケンスは自分で設計する
            // (本サンプルはリクエスト・レスポンス型の通信シーケンス)。

            // 名前付きパイプ(クライアント)
            // 双方向のメッセージ ストリーム
            NamedPipeClientStream s = null;
            MemoryStream ms = null;

            byte[] buff = new byte[256];
            byte[] byt = null;

            int bytSize = 0;
            string str = "";

            int frequency = this.Frequency[Thread.CurrentThread.ManagedThreadId];
            string message = this.Message[Thread.CurrentThread.ManagedThreadId];

            // スレッドID
            int managedThreadId = Thread.CurrentThread.ManagedThreadId;

            try
            {
                // 名前付きパイプ(クライアント)を生成
                s = new NamedPipeClientStream(
                    ".", "mypipe", PipeDirection.InOut);

                s.Connect(3 * 1000);
                //s.ReadTimeout = 3 * 1000;
                //s.WriteTimeout = 3 * 1000;

                // 接続を表示
                this.SetResult_Client(
                    string.Format("接続 - ThreadId:{0}" , managedThreadId));

                // メッセージをn回送信
                for (int i = 1; i <= frequency; i++)
                {
                    // メッセージを送信
                    str = i.ToString() + "-" + message + "<end-send>";
                    byt = Encoding.UTF8.GetBytes(str);
                    s.Write(byt, 0, byt.Length);

                    // 送信メッセージを表示
                    this.SetResult_Client(
                        string.Format("({0})送信:{1}", managedThreadId, str));

                    // 受信処理
                    ms = new MemoryStream();

                    while (true)
                    {
                        // メッセージ(の一部)を受信
                        bytSize = s.Read(buff, 0, buff.Length); //(待機)

                        // 受信したメッセージを蓄積
                        ms.Write(buff, 0, bytSize);

                        // 受信したメッセージを文字列に変換
                        str = Encoding.UTF8.GetString(ms.ToArray());

                        // ここでは、<end-send>と送られるまで受信を続行する。
                        if (str.IndexOf("<end-send>") != -1)
                        {
                            // シーケンス制御文字を消去
                            str = str.Replace("<end-send>", "");
                            break;
                        }
                    }

                    // 受信メッセージを表示
                    this.SetResult_Client(
                        string.Format("({0})受信:{1}", managedThreadId, str));
                }

                // 全送信の終了
                str = "終わり<end-connect>";
                byt = Encoding.UTF8.GetBytes(str);
                s.Write(byt, 0, byt.Length);

                // 送信メッセージを表示
                this.SetResult_Client(
                        string.Format("({0})送信:{1}", managedThreadId, str));
            }
            catch (Exception ex)
            {
                // エラーを表示
                this.SetResult_Client(
                    string.Format("({0})エラー:{1}", managedThreadId, ex.ToString()));
            }
            finally
            {
                if (s != null)
                {
                    // TCPストリーム ソケットをクローズ
                    s.Close();
                }

                // 切断を表示
                this.SetResult_Client(
                    string.Format(
                        "切断 - ThreadId:{0}" , managedThreadId));
            }
        }