private static void PipesReader(string pipeName)
        {
            try
            {

                using (var pipeReader = new NamedPipeServerStream(pipeName, PipeDirection.In))
                {
                    pipeReader.WaitForConnection();
                    WriteLine("reader connected");
                    const int BUFFERSIZE = 256;

                    bool completed = false;
                    while (!completed)
                    {
                        byte[] buffer = new byte[BUFFERSIZE];
                        int nRead = pipeReader.Read(buffer, 0, BUFFERSIZE);
                        string line = Encoding.UTF8.GetString(buffer, 0, nRead);
                        WriteLine(line);
                        if (line == "bye") completed = true;
                    }
                }
                WriteLine("completed reading");
                ReadLine();
            }
            catch (Exception ex)
            {
                WriteLine(ex.Message);
            }
        }
        private async void StartInternal(CancellationToken cancellationToken)
        {
            byte[] buffer = new byte[256];
            var commandBuilder = new StringBuilder();

            var serverStream = new NamedPipeServerStream(this.PipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 0, 0);

            using (cancellationToken.Register(() => serverStream.Close()))
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    await Task.Factory.FromAsync(serverStream.BeginWaitForConnection, serverStream.EndWaitForConnection, TaskCreationOptions.None);

                    int read = await serverStream.ReadAsync(buffer, 0, buffer.Length);
                    commandBuilder.Append(Encoding.ASCII.GetString(buffer, 0, read));

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

                    var response = this.HandleReceivedCommand(commandBuilder.ToString());
                    var responseBytes = Encoding.ASCII.GetBytes(response);
                    serverStream.Write(responseBytes, 0, responseBytes.Length);

                    serverStream.WaitForPipeDrain();
                    serverStream.Disconnect();

                    commandBuilder.Clear();
                }
            }
        }
    public static void ClientSendsByteServerReceives()
    {
        using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.In))
        {
            byte[] sent = new byte[] { 123 };
            byte[] received = new byte[] { 0 };
            Task t = Task.Run(() =>
                {
                    using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foo", PipeDirection.Out))
                    {
                        client.Connect();
                        Assert.True(client.IsConnected);

                        client.Write(sent, 0, 1);
                    }
                });
            server.WaitForConnection();
            Assert.True(server.IsConnected);

            int bytesReceived = server.Read(received, 0, 1);
            Assert.Equal(1, bytesReceived);

            t.Wait();
            Assert.Equal(sent[0], received[0]);
        }
    }
        private void PipeThreadStart()
        {
            PipeSecurity pSec = new PipeSecurity();
            PipeAccessRule pAccRule = new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null)
            , PipeAccessRights.ReadWrite | PipeAccessRights.Synchronize, System.Security.AccessControl.AccessControlType.Allow);
            pSec.AddAccessRule(pAccRule);

            using (_pipeServer = new NamedPipeServerStream("NKT_SQLINTERCEPT_PIPE",
                PipeDirection.InOut,
                NamedPipeServerStream.MaxAllowedServerInstances,
                PipeTransmissionMode.Byte,
                PipeOptions.None,
                MAX_STRING_CCH * 2,
                MAX_STRING_CCH * 2,
                pSec,
                HandleInheritability.Inheritable))
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("(pipe thread) Waiting for connection...");
                Console.ForegroundColor = ConsoleColor.Gray;

                try
                {
                    _pipeServer.WaitForConnection();

                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("(pipe thread) Client connected.");
                    Console.ForegroundColor = ConsoleColor.Gray;

                    while (true)
                    {
                        byte[] readBuf = new byte[MAX_STRING_CCH * 2];

                        int cbRead = _pipeServer.Read(readBuf, 0, MAX_STRING_CCH * 2);

                        string str = Encoding.Unicode.GetString(readBuf, 0, cbRead);

                        Console.WriteLine(str);
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine("--------------------------------------------------------");
                        Console.ForegroundColor = ConsoleColor.Gray;

                        if (_blockQuery)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("(pipe thread) QUERY ABORTED");
                            Console.ForegroundColor = ConsoleColor.Gray;
                        }

                    }
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine("(pipethread) Pipe or data marshaling operation exception! ({0})", ex.Message);
                }
            }
        }
Exemple #5
0
		static void SetupPipeWait(App app)
		{
			var pipe = new NamedPipeServerStream(IPCName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
			pipe.BeginWaitForConnection(result =>
			{
				pipe.EndWaitForConnection(result);

				var buf = new byte[sizeof(int)];
				pipe.Read(buf, 0, buf.Length);
				var len = BitConverter.ToInt32(buf, 0);
				buf = new byte[len];
				pipe.Read(buf, 0, buf.Length);
				var commandLine = Coder.BytesToString(buf, Coder.CodePage.UTF8);

				app.Dispatcher.Invoke(() => app.CreateWindowsFromArgs(commandLine));

				SetupPipeWait(app);
			}, null);
		}
        public bool ProcessMessages(NamedPipeServerStream server)
        {
            try
            {
                //BinaryReader would throw EndOfStreamException

                byte[] buffer = new byte[4];
                if (server.Read(buffer, 0, 4) == 0)
                    return false;

                int count = BitConverter.ToInt32(buffer, 0);
                var rawTouchDatas = new List<RawTouchData>(count);
                for (int i = 0; i < count; i++)
                {
                    buffer = new byte[13];

                    server.Read(buffer, 0, 1);
                    server.Read(buffer, 1, 4);
                    server.Read(buffer, 5, 4);
                    server.Read(buffer, 9, 4);

                    bool tip = BitConverter.ToBoolean(buffer, 0);
                    int contactIdentifier = BitConverter.ToInt32(buffer, 1);
                    int x = BitConverter.ToInt32(buffer, 5);
                    int y = BitConverter.ToInt32(buffer, 9);

                    rawTouchDatas.Add(new RawTouchData(tip, contactIdentifier, new Point(x, y)));
                }

                _synchronizationContext.Post(o =>
                {
                    PointsIntercepted?.Invoke(this, new RawPointsDataMessageEventArgs(rawTouchDatas));
                }, null);
            }
            catch (Exception exception)
            {
                Logging.LogException(exception);
                return false;
            }
            return true;
        }
    protected void ThreadStartServer() {
      // Some idiot MS intern must have written the blocking part of pipes. There is no way to
      // cancel WaitForConnection, or ReadByte. (pipes introduced in 3.5, I thought one time I read
      // that 4.0 added an abort option, but I cannot find it)
      // If you set Async as the option, but use sync calls, .Close can kind of kill them.
      // It causes exceptions to be raised in WaitForConnection and ReadByte (possibly due to another
      // issue with threads and exceptions without handlers, maybe check again later), but they just
      // loop over and over on it... READ however with the async option WILL exit with 0....
      // Its like VB1 and adding to sorted listboxes over all again... no one dogfooded this stuff.
      // And yes we could use async.. but its SOOO much messier and far more complicated than it ever
      // should be.
      //
      // Here is an interesting approach using async and polling... If need be we can go that way:
      // http://stackoverflow.com/questions/2700472/how-to-terminate-a-managed-thread-blocked-in-unmanaged-code

      while (!KillThread)
      {
        // Loop again to allow mult incoming connections between debug sessions
        try
        {
          using (mPipe = new NamedPipeServerStream(mPipeName, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous)) {
            mPipe.WaitForConnection();

            ushort xCmd;
            int xSize;
            while (mPipe.IsConnected && !KillThread) {
              xCmd = (ushort)(ReadByte() << 8);
              xCmd |= ReadByte();

              xSize = ReadByte() << 24;
              xSize = xSize | ReadByte() << 16;
              xSize = xSize | ReadByte() << 8;
              xSize = xSize | ReadByte();

              byte[] xMsg = new byte[xSize];
              mPipe.Read(xMsg, 0, xSize);

              if (DataPacketReceived != null)
              {
                  DataPacketReceived(xCmd, xMsg);
              }
            }
          }
        } catch (Exception) {
          // Threads MUST have an exception handler
          // Otherwise there are side effects when an exception occurs
        }
      }
    }
 public static void createPipeServer()
 {
     Decoder decoder = Encoding.Default.GetDecoder();
     Byte[] bytes = new Byte[BufferSize];
     char[] chars = new char[BufferSize];
     int numBytes = 0;
     StringBuilder msg = new StringBuilder();
     ownerInvoker = new Invoker(owner);
     ownerInvoker.sDel = ExecuteCommand;
     pipeName = "BarcodeServer";
     try
     {
         pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.In, 1,
                                                PipeTransmissionMode.Message,
                                                PipeOptions.Asynchronous);
         while (true)
         {
             pipeServer.WaitForConnection();
             do
             {
                 msg.Length = 0;
                 do
                 {
                     numBytes = pipeServer.Read(bytes, 0, BufferSize);
                     if (numBytes > 0)
                     {
                         int numChars = decoder.GetCharCount(bytes, 0, numBytes);
                         decoder.GetChars(bytes, 0, numBytes, chars, 0, false);
                         msg.Append(chars, 0, numChars);
                     }
                 } while (numBytes > 0 && !pipeServer.IsMessageComplete);
                 decoder.Reset();
                 if (numBytes > 0)
                 {
                     ownerInvoker.Invoke(msg.ToString());
                 }
             } while (numBytes != 0);
             pipeServer.Disconnect();
         }
     }
     catch (Exception)
     {
         //throw new Exception("Failed to create pipeServer! the detailed messages are: " + ex.Message);
         //MessageBox.Show(ex.Message);
     }
 }
        public static void createPipeServer()
        {
            Decoder decoder = Encoding.Default.GetDecoder();
            Byte[] bytes = new Byte[BufferSize];
            char[] chars = new char[BufferSize];
            int numBytes = 0;
            StringBuilder msg = new StringBuilder();

            try
            {
                pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
                while (true)
                {
                    pipeServer.WaitForConnection();

                    do
                    {
                        msg.Length = 0;
                        do
                        {
                            numBytes = pipeServer.Read(bytes, 0, BufferSize);
                            if (numBytes > 0)
                            {
                                int numChars = decoder.GetCharCount(bytes, 0, numBytes);
                                decoder.GetChars(bytes, 0, numBytes, chars, 0, false);
                                msg.Append(chars, 0, numChars);
                            }
                        } while (numBytes > 0 && !pipeServer.IsMessageComplete);
                        decoder.Reset();
                        if (numBytes > 0)
                        {
                            //Notify the UI for message received
                            if (owner != null)
                                owner.Dispatcher.Invoke(DispatcherPriority.Send, new Action<string>(owner.OnMessageReceived), msg.ToString());
                            //ownerInvoker.Invoke(msg.ToString());
                        }
                    } while (numBytes != 0);
                    pipeServer.Disconnect();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #10
0
        static void Main(string[] args)
        {
            Console.WriteLine("Creating pipe {0}", PIPE_NAME);
            NamedPipeServerStream pipeServer = new NamedPipeServerStream(
                PIPE_NAME,
                PipeDirection.InOut,
                10,
                PipeTransmissionMode.Message,
                PipeOptions.None
                );

            Console.WriteLine("Waiting for connection.");
            pipeServer.WaitForConnection();

            Console.WriteLine("Client connected.");

            int bytes_read;
            while(true)
            {
                Byte[] buffer = new Byte[4096];
                StringBuilder sb = new StringBuilder();
                do
                {
                    bytes_read = pipeServer.Read(buffer, 0, buffer.Length);
                    sb.Append(Encoding.UTF8.GetChars(buffer, 0, bytes_read));
                    if (pipeServer.IsMessageComplete)
                    {
                        break;
                    }
                }
                while (!pipeServer.IsMessageComplete);

                if (bytes_read == 0)
                {
                    Console.WriteLine("Received empty message, quitting.");
                    break;
                }

                Console.WriteLine("Message received: {0}", sb.ToString());
            }

            Console.WriteLine("Done");
        }
Exemple #11
0
        static void Test2()
        {
            NamedPipeServerStream stream = new NamedPipeServerStream("MaxUnityBridge");
            stream.WaitForConnection();

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

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

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

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

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


            } while (true);
        }
Exemple #12
0
        public void StartPipeServer()
        {
            serverStream = new NamedPipeServerStream("zjlrcpipe",
                PipeDirection.InOut,
                10,
                PipeTransmissionMode.Message,
                PipeOptions.None);
            serverStream.ReadMode = PipeTransmissionMode.Message;
            Byte[] bytes = new Byte[1024];
            UTF8Encoding encoding = new UTF8Encoding();
            int numBytes;
            while (running)
            {

                serverStream.WaitForConnection();
                string message = "";
                do
                {
                    numBytes = serverStream.Read(bytes, 0, bytes.Length);

                    message += encoding.GetString(bytes, 0, numBytes);
                } while (!serverStream.IsMessageComplete);

                string[] pas = message.Split('|');
                if (null != pas && pas.Length >= 3)
                {
                    if (!(pas[0] == "exit" && pas[1] == "exit" && pas[2] == "exit"))
                        main.Dispatcher.Invoke(main.searchLrcByZLP, pas[0], pas[1], pas[2]);
                    else
                        running = false;
                }

                serverStream.Disconnect();

            }
            serverStream.Dispose();
        }
Exemple #13
0
 private void Init()
 {
     if (PipeExists(PIPENAME)) {
         using (NamedPipeClientStream client = new NamedPipeClientStream(PIPENAME)) {
             try {
                 client.Connect(2000);
                 client.Write(SHOW, 0, SHOW.Length);
                 client.WaitForPipeDrain();
             }
             catch {
             }
         }
         Environment.Exit(1);
     }
     using (NamedPipeServerStream server = new NamedPipeServerStream(PIPENAME)) {
         while (true) {
             server.WaitForConnection();
             byte[] data = new byte[255];
             int count = server.Read(data, 0, data.Length);
             string msg = Encoding.ASCII.GetString(data, 0, count).ToUpper();
             if (msg.Equals("SHOW")) {
                 main.Invoke(new MethodInvoker(delegate
                 {
                     main.Show();
                     main.WindowState = FormWindowState.Normal;
                 }));
             }
             else if (msg.Equals("BREAK")) {
                 break;
             }
             else if (msg.Equals("EXIT")) {
                 Environment.Exit(0);
             }
             server.Disconnect();
         }
     }
 }
    public static async Task ServerCloneTests()
    {
        const string pipeName = "fooclone";
        byte[] msg1 = new byte[] { 5, 7, 9, 10 };
        byte[] received1 = new byte[] { 0, 0, 0, 0 };

        using (NamedPipeServerStream serverBase = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte))
        using (NamedPipeClientStream client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, PipeOptions.None))
        {
            Task clientTask = Task.Run(() =>
            {
                client.Connect();
                client.Write(msg1, 0, msg1.Length);
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    Assert.Equal(1, client.NumberOfServerInstances);
                }
            });

            serverBase.WaitForConnection();
            using (NamedPipeServerStream server = new NamedPipeServerStream(PipeDirection.In, false, true, serverBase.SafePipeHandle))
            {
                int len1 = server.Read(received1, 0, msg1.Length);
                Assert.Equal(msg1.Length, len1);
                Assert.Equal(msg1, received1);
                await clientTask;
            }
        }
    }
Exemple #15
0
        private void ReadThreadStart(NamedPipeServerStream decodePipe, Process encoder)
        {
            const int bufSize = 1024 * 1024;
            byte[] buffer = new byte[bufSize];

            decodePipe.WaitForConnection();
            while (decodePipe.IsConnected && !encoder.HasExited)
            {
                int readCnt = decodePipe.Read(buffer, 0, bufSize);
                encoder.StandardInput.BaseStream.Write(buffer, 0, readCnt);
            }
            encoder.StandardInput.BaseStream.Close();
        }
Exemple #16
0
        //private const int ALLSELECT = 60;
        //private const int CUT = 52;
        static void Main(string[] args)
        {
            string[] simpleNames = { "Yukari", "Maki", "Zunko", "Akane", "Aoi", "Koh" };
            string[] voiceroidNames = {
                                          "VOICEROID+ 結月ゆかり EX",
                                          "VOICEROID+ 民安ともえ EX",
                                          "VOICEROID+ 東北ずん子 EX",
                                          "VOICEROID+ 琴葉茜",
                                          "VOICEROID+ 琴葉葵",
                                          "VOICEROID+ 水奈瀬コウ EX"
                                      };
            Console.WriteLine("");

            //引数のチェック
            if (args.Length < 1) {
                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 selectedSimple = null;
            int selectedIndex = 0;
            for (int i = 0; i < simpleNames.Length; i++) {
                if (args[0].CompareTo(simpleNames[i]) == 0) {
                    selectedSimple = simpleNames[i];
                    selectedIndex = i;
                    break;
                }
            }
            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;
            }
            //VOICEROID.exeの起動チェック
            Process[] apps = Process.GetProcessesByName("VOICEROID");
            if (apps.Length < 1)
            {
                Console.WriteLine("プロセスに" + voiceroidNames[selectedIndex] + "のVOICEROID.exeがありません. " + voiceroidNames[selectedIndex] + "を起動してください.");
                return;
            }
            //VOICEROID.exeのプロセス取得
            AutomationElement ae = null;
            foreach (Process app in apps)
            {
                AutomationElement rootHandle = AutomationElement.FromHandle(app.MainWindowHandle);
                foreach(string voiceroidName in voiceroidNames) {
                    string name = rootHandle.Current.Name;
                    if (name.CompareTo(voiceroidNames[selectedIndex]) == 0 || name.CompareTo(voiceroidNames[selectedIndex]+"*") == 0) ae = rootHandle;
                }
            }
            //起動しているVOICEROID.exeと指定されたキャラクターのVOICEROID.exeが一致しなかった時
            if(ae == 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が起動していません. 他の名前を指定するか, 指定した名前のVOICEROID.exeを起動してください: " + mergeName);
                return;
            }
            Console.Clear();
            //ウィンドウにフォーカスをあわせる
            ae.SetFocus();

            //テキストボックス、再生ボタン、停止ボタンのGUIコントロール取得
            AutomationElement txtForm = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtMain", PropertyConditionFlags.IgnoreCase));
            IntPtr txtFormHandle = IntPtr.Zero;
            try {
                txtFormHandle = (IntPtr)txtForm.Current.NativeWindowHandle;
            }
            catch (NullReferenceException e) {
                //ハンドルが取得できなかった場合、ウィンドウが見つかっていない
                Console.WriteLine(voiceroidNames[selectedIndex] + "のウィンドウが取得できませんでした. 最小化されているか, ほかのプロセスによってブロックされています.");
                return;
            }
            //テキストボックスのハンドルを取得
            IntPtr txtControl = FindWindowEx(txtFormHandle, IntPtr.Zero, null, null);
            //再生ボタンのハンドルを取得
            AutomationElement btnPlay = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "btnPlay", PropertyConditionFlags.IgnoreCase));
            IntPtr btnControl = (IntPtr)btnPlay.Current.NativeWindowHandle;
            //停止ボタンのハンドルを取得
            AutomationElement btnStop = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "btnStop", PropertyConditionFlags.IgnoreCase));
            IntPtr stpControl = (IntPtr)btnStop.Current.NativeWindowHandle;

            //音量、速度、高さ、抑揚のテキストボックスのコントロールを取得
            AutomationElement txtVol = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtVolume", PropertyConditionFlags.IgnoreCase));
            AutomationElement txtSpd = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtSpeed", PropertyConditionFlags.IgnoreCase));
            AutomationElement txtPit = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtPitch", PropertyConditionFlags.IgnoreCase));
            AutomationElement txtEmp = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtEmphasis", PropertyConditionFlags.IgnoreCase));

            //音声効果の画面が表示されていない時の処理
            if (txtVol == null || txtSpd == null || txtPit == null || txtEmp == null) {
                Console.WriteLine("音声効果の画面を展開しています...");
                Thread.Sleep(100);

                //音声チューニングのタブを取得
                AutomationElementCollection tabs = ae.FindAll(TreeScope.Descendants,
                    new PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "タブ項目", PropertyConditionFlags.IgnoreCase));

                //音声チューニングのタブが取得できない時の処理
                if (tabs.Count < 1) {
                    AutomationElementCollection menues = ae.FindAll(TreeScope.Descendants,
                        new PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "メニュー項目", PropertyConditionFlags.IgnoreCase));

                    //音声チューニングのウィンドウを表示する
                    foreach (AutomationElement menu in menues) {
                        if (menu.Current.Name.CompareTo("音声チューニング(T)") == 0) {
                            object ipShowTuning;
                            if (menu.TryGetCurrentPattern(InvokePattern.Pattern, out ipShowTuning)) {
                                ((InvokePattern)ipShowTuning).Invoke();
                                Thread.Sleep(1000);
                            }
                        }
                    }

                    //再度音声チューニング
                    tabs = ae.FindAll(TreeScope.Descendants,
                    new PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "タブ項目", PropertyConditionFlags.IgnoreCase));
                }

                //音声効果のタブを探す
                foreach (AutomationElement tab in tabs) {
                    if (tab.Current.Name.CompareTo("音声効果") == 0) {
                        object ipShowSoundEffect;
                        if (tab.TryGetCurrentPattern(SelectionItemPattern.Pattern, out ipShowSoundEffect)) {
                            ((SelectionItemPattern)ipShowSoundEffect).Select();
                            Thread.Sleep(1000);
                        }
                    }
                }

                //再度、音量、速度、高さ、抑揚のテキストボックスのコントロールを取得
                txtVol = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtVolume", PropertyConditionFlags.IgnoreCase));
                txtSpd = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtSpeed", PropertyConditionFlags.IgnoreCase));
                txtPit = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtPitch", PropertyConditionFlags.IgnoreCase));
                txtEmp = ae.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "txtEmphasis", PropertyConditionFlags.IgnoreCase));
            }

            //再度、音量、速度、高さ、抑揚のハンドルを取得
            IntPtr txtVolControl = (IntPtr)txtVol.Current.NativeWindowHandle;
            IntPtr txtSpdControl = (IntPtr)txtSpd.Current.NativeWindowHandle;
            IntPtr txtPitControl = (IntPtr)txtPit.Current.NativeWindowHandle;
            IntPtr txtEmpControl = (IntPtr)txtEmp.Current.NativeWindowHandle;

            //InvokePattern ipBtnPlay = (InvokePattern)btnPlay.GetCurrentPattern(InvokePattern.Pattern);
            //ValuePattern vpTxtVol = (ValuePattern)txtVol.GetCurrentPattern(ValuePattern.Pattern);
            //ValuePattern vpTxtSpd = (ValuePattern)txtSpd.GetCurrentPattern(ValuePattern.Pattern);
            //ValuePattern vpTxtPit = (ValuePattern)txtPit.GetCurrentPattern(ValuePattern.Pattern);
            //ValuePattern vpTxtEmp = (ValuePattern)txtEmp.GetCurrentPattern(ValuePattern.Pattern);

            string btnName = btnPlay.Current.Name;
            string message = "";
            Console.WriteLine("[voiceroid_talker" +selectedSimple + "]のサーバーを開始しています...");

            //メインループ
            while (true) {
                string clientMessage;
                string[] messages;
                string messageVol = "1.0";
                string messageSpd = "1.0";
                string messagePit = "1.0";
                string messageEmp = "1.0";
                //通信セッションの開始
                try
                {
                    using (NamedPipeServerStream server = new NamedPipeServerStream("voiceroid_talker" + selectedSimple))
                    {
                        Console.WriteLine("クライアントからのメッセージを待っています...");
                        server.WaitForConnection();

                        byte[] buffer = new byte[1024];
                        server.Read(buffer, 0, buffer.Length);
                        string messageRaw = UnicodeEncoding.Unicode.GetString(buffer);
                        clientMessage = messageRaw.Trim('\0');
                        //通信メッセージの内容をパースする
                        messages = clientMessage.Split(';');
                        if (messages.Length == 1)
                        {
                            message = clientMessage;
                            if (message.CompareTo("exit") == 0) break;
                        }
                        else
                        {
                            message = messages[0];
                        }
                        //音量のパラメータを取得する
                        if (messages.Length >= 2)
                        {
                            float val = 0.0f;
                            if (float.TryParse(messages[1], out val)) messageVol = val.ToString();
                        }
                        //速度のパラメータを取得する
                        if (messages.Length >= 3)
                        {
                            float val = 0.0f;
                            if (float.TryParse(messages[2], out val)) messageSpd = val.ToString();
                        }
                        //高さのパラメータを取得する
                        if (messages.Length >= 4)
                        {
                            float val = 0.0f;
                            if (float.TryParse(messages[3], out val)) messagePit = val.ToString();
                        }
                        //抑揚のパラメータを取得する
                        if (messages.Length >= 5)
                        {
                            float val = 0.0f;
                            if (float.TryParse(messages[4], out val)) messageEmp = val.ToString();
                        }

                        //音量、速度、高さ、抑揚のテキストボックスに値を入力
                        SendMessage(txtVolControl, WM_SETTEXT, IntPtr.Zero, messageVol);
                        PostMessage(txtVolControl, WM_KEYDOWN, (IntPtr)VK_RETURN, null);

                        SendMessage(txtSpdControl, WM_SETTEXT, IntPtr.Zero, messageSpd);
                        PostMessage(txtSpdControl, WM_KEYDOWN, (IntPtr)VK_RETURN, null);

                        SendMessage(txtPitControl, WM_SETTEXT, IntPtr.Zero, messagePit);
                        PostMessage(txtPitControl, WM_KEYDOWN, (IntPtr)VK_RETURN, null);

                        SendMessage(txtEmpControl, WM_SETTEXT, IntPtr.Zero, messageEmp);
                        PostMessage(txtEmpControl, WM_KEYDOWN, (IntPtr)VK_RETURN, null);

                        Thread.Sleep(10);

                        //テキストボックスにメッセージを入れ、再生する
                        SendMessage(txtControl, WM_SETTEXT, IntPtr.Zero, message);
                        PostMessage(stpControl, WM_CLICK, IntPtr.Zero, null);
                        PostMessage(btnControl, WM_CLICK, IntPtr.Zero, null);

                        //ipBtnPlay.Invoke();
                        Thread.Sleep(100);

                        //レスポンス用メッセージをクライアントに送信
                        byte[] response = UnicodeEncoding.Unicode.GetBytes("OK");
                        server.Write(response, 0, 2);

                        //セッションを終了する
                        server.Close();
                    }
                } catch(IOException e) {
                    //セッション作成時にエラーが発生した場合
                    Console.WriteLine("通信セッションの作成に失敗しました. 他のサーバーによって, 同名のセッションが開始されている可能性があります.");
                    break;
                }
            }
        }
Exemple #17
0
        public void ServiceRequest(NamedPipeServerStream nss)
        {
            var msgbuf = new List<byte>(8192);
            var rxbuf = new byte[256 * 1024];
            int count = 0;


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

            } while (!nss.IsMessageComplete);

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

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

            nss.WaitForPipeDrain();
            nss.Disconnect();
            
            Logging.Emit("request done");
        }
        /// <summary>サーバ起動 - listenerスレッド関数</summary>
        private void ListeningNamedPipe()
        {
            // 通信シーケンスは自分で設計する
            // (本サンプルはリクエスト・レスポンス型の通信シーケンス)。

            // 名前付きパイプ(サーバ)
            NamedPipeServerStream np = null;
            MemoryStream ms = null;

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

            try
            {
                // 名前付きパイプ(サーバ)を生成
                // ※ 双方向のメッセージ ストリーム(最大5個オープン可能)
                np = new NamedPipeServerStream(
                        "mypipe", PipeDirection.InOut, 5);

                // Listening開始を表示
                this.SetResult_Svr(
                    string.Format("Listening開始! - ThreadId:{0}", managedThreadId));

                np.WaitForConnection(); //(待機)

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

                // 終了させるまで延々と読み続ける。
                bool disConnect = false;

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

                int bytSize = 0;

                string msg = "";

                do
                {
                    ms = new MemoryStream();

                    // 受信処理

                    while (true)
                    {
                        // 送信元(=クライアント)毎に読み込むことができる。
                        bytSize = np.Read(buff, 0, buff.Length);

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

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

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

                        // ここでは、シーケンス制御文字の
                        // <end-connect>が送られるまで受信を続行する。
                        if (msg.IndexOf("<end-connect>") != -1)
                        {
                            // これがきたときに切断
                            disConnect = true;

                            // シーケンス制御文字を消去
                            msg = msg.Replace("<end-connect>", "");
                            break;
                        }
                    }

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

                    // 反転処理
                    msg = CmnClass.strrev(msg);

                    // 送信処理

                    if (!disConnect) // <end-connect>の際は、接続がクライアントから切断されている。
                    {
                        // 送信処理
                        byt = Encoding.UTF8.GetBytes(msg + "<end-send>");
                        np.Write(byt, 0, byt.Length);

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

                } while (!disConnect);

            }
            catch (Exception ex)
            {
                // エラーを表示
                this.SetResult_Svr(
                    string.Format("({0})エラー:{1}", managedThreadId, ex.ToString()));
            }
            finally
            {
                if (np != null)
                {
                    // 名前付きパイプ(サーバ)をクローズ
                    np.Close();
                }
            }

            // 切断を表示
            this.SetResult_Svr(
                string.Format("切断 - ThreadId:{0}", managedThreadId));
        }
Exemple #19
0
        private string ReadStringFromPipe(NamedPipeServerStream pipe)
        {
            uint length = ReadNumberFromPipe(pipe);

            byte[] buffer = new byte[length * 2];
            pipe.Read(buffer, 0, buffer.Length);

            return Encoding.Unicode.GetString(buffer);
        }
        private void ReadMessage(NamedPipeServerStream namedPipeServer)
        {
            var connectEvent = new AutoResetEvent(false);

            var connectResult = namedPipeServer.BeginWaitForConnection(ar => connectEvent.Set(), null);
            WaitHandle.WaitAny(new WaitHandle[] {_cancelConnectionEvent, connectEvent});

            if (_stopReading)
                return;

            namedPipeServer.EndWaitForConnection(connectResult);            

            byte[] data;
            
            using (var ms = new MemoryStream())
            {
                var buffer = new byte[256 * 1024];

                int bytesRead;
                while ((bytesRead = namedPipeServer.Read(buffer, 0, buffer.Length)) > 0)
                    ms.Write(buffer, 0, bytesRead);

                data = ms.ToArray();
            }

            namedPipeServer.Disconnect();

            HandleMessage(data);
        }
    public static void ServerCloneTests()
    {
        const string pipeName = "fooclone";
        byte[] msg1 = new byte[] { 5, 7, 9, 10 };
        byte[] received1 = new byte[] { 0, 0, 0, 0 };

        using (NamedPipeServerStream serverBase = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte))
        {
            using (NamedPipeServerStream server = new NamedPipeServerStream(PipeDirection.InOut, false, false, serverBase.SafePipeHandle))
            {
                using (NamedPipeClientStream client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None))
                {
                    Task clientTask = Task.Run(() =>
                    {
                        client.Connect();

                        client.Write(msg1, 0, msg1.Length);

                        int serverCount = client.NumberOfServerInstances;
                        Assert.Equal(1, serverCount);
                    });
                }

                server.WaitForConnection();
                int len1 = server.Read(received1, 0, msg1.Length);
                Assert.Equal(msg1.Length, len1);
                Assert.Equal(msg1, received1);
            }
        }
    }
    public static void ClientServerMessages()
    {
        byte[] msg1 = new byte[] { 5, 7, 9, 10 };
        byte[] msg2 = new byte[] { 2, 4 };
        byte[] received1 = new byte[] { 0, 0, 0, 0 };
        byte[] received2 = new byte[] { 0, 0 };
        byte[] received3 = new byte[] { 0, 0, 0, 0}; ;

        using (NamedPipeServerStream server = new NamedPipeServerStream("foomsg", PipeDirection.InOut, 1, PipeTransmissionMode.Message))
        {
            using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foomsg", PipeDirection.InOut, PipeOptions.None, System.Security.Principal.TokenImpersonationLevel.Identification))
            {
                Task clientTask = Task.Run(() =>
                {
                    client.Connect();
                    
                    client.Write(msg1, 0, msg1.Length);
                    client.Write(msg2, 0, msg2.Length);
                    client.Write(msg1, 0, msg1.Length);

                    int serverCount = client.NumberOfServerInstances;
                    Assert.Equal(1, serverCount);
                });

                server.WaitForConnection();
                int len1 = server.Read(received1, 0, msg1.Length);
                Assert.True(server.IsMessageComplete);
                Assert.Equal(msg1.Length, len1);
                Assert.Equal(msg1, received1);

                int len2 = server.Read(received2, 0, msg2.Length);
                Assert.True(server.IsMessageComplete);
                Assert.Equal(msg2.Length, len2);
                Assert.Equal(msg2, received2);

                int len3 = server.Read(received3, 0, msg1.Length - 1);  // read one less than message
                Assert.False(server.IsMessageComplete);
                Assert.Equal(msg1.Length - 1, len3);

                int len4 = server.Read(received3, len3, received3.Length - len3);
                Assert.True(server.IsMessageComplete);
                Assert.Equal(msg1.Length, len3 + len4);
                Assert.Equal(msg1, received3);

                string userName = server.GetImpersonationUserName();    // not sure what to test here that will work in all cases
            }
        }
    }
Exemple #23
0
        public bool StartServer(string strEventName, string strPipeName, Action<CMD_STREAM, CMD_STREAM> pfnCmdProc)
        {
            if (pfnCmdProc == null || strEventName.Length == 0 || strPipeName.Length == 0)
            {
                return false;
            }
            if (m_ServerThread != null)
            {
                return false;
            }

            m_StopFlag = false;
            m_PulseEvent = new AutoResetEvent(false);
            m_ServerThread = new Thread(new ThreadStart(() =>
            {
                using (EventWaitHandle eventConnect = new EventWaitHandle(false, EventResetMode.AutoReset, strEventName))
                using (NamedPipeServerStream pipe = new NamedPipeServerStream(
                           strPipeName.Substring(strPipeName.StartsWith("\\\\.\\pipe\\", StringComparison.OrdinalIgnoreCase) ? 9 : 0),
                           PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
                {
                    while (m_StopFlag == false)
                    {
                        pipe.BeginWaitForConnection(asyncResult =>
                        {
                            try
                            {
                                if (m_StopFlag == false)
                                {
                                    pipe.EndWaitForConnection(asyncResult);
                                    m_PulseEvent.Set();
                                }
                            }
                            catch (ObjectDisposedException)
                            {
                            }
                        }, null);
                        eventConnect.Set();
                        m_PulseEvent.WaitOne();
                        if (pipe.IsConnected)
                        {
                            try
                            {
                                byte[] bHead = new byte[8];
                                if (pipe.Read(bHead, 0, 8) == 8)
                                {
                                    CMD_STREAM stCmd = new CMD_STREAM();
                                    stCmd.uiParam = BitConverter.ToUInt32(bHead, 0);
                                    stCmd.uiSize = BitConverter.ToUInt32(bHead, 4);
                                    stCmd.bData = stCmd.uiSize == 0 ? null : new byte[stCmd.uiSize];
                                    if (stCmd.uiSize == 0 || pipe.Read(stCmd.bData, 0, stCmd.bData.Length) == stCmd.bData.Length)
                                    {
                                        CMD_STREAM stRes = new CMD_STREAM();
                                        pfnCmdProc.Invoke(stCmd, stRes);
                                        if (stRes.uiParam == (uint)ErrCode.CMD_NEXT)
                                        {
                                            // Emun用の繰り返しは対応しない
                                            throw new InvalidOperationException();
                                        }
                                        else if (stRes.uiParam != (uint)ErrCode.CMD_NO_RES)
                                        {
                                            BitConverter.GetBytes(stRes.uiParam).CopyTo(bHead, 0);
                                            BitConverter.GetBytes(stRes.uiSize).CopyTo(bHead, 4);
                                            pipe.Write(bHead, 0, 8);
                                            if (stRes.uiSize != 0 && stRes.bData != null && stRes.bData.Length >= stRes.uiSize)
                                            {
                                                pipe.Write(stRes.bData, 0, (int)stRes.uiSize);
                                            }
                                        }
                                    }
                                }
                                pipe.WaitForPipeDrain();
                                pipe.Disconnect();
                            }
                            catch
                            {
                                // Read & Write 中に切断されると例外が起きるはずなので一応 catch しておく
                            }
                        }
                    }
                }
            }));
            m_ServerThread.Start();

            return true;
        }
        /// <summary>
        /// Use the pipe classes in the System.IO.Pipes namespace to create the 
        /// named pipe. This solution is recommended.
        /// </summary>
        public static void Run()
        {
            NamedPipeServerStream pipeServer = null;

            try
            {
                // Prepare the security attributes (the pipeSecurity parameter in
                // the constructor of NamedPipeServerStream) for the pipe. This
                // is optional. If pipeSecurity of NamedPipeServerStream is null,
                // the named pipe gets a default security descriptor.and the
                // handle cannot be inherited. The ACLs in the default security
                // descriptor of a pipe grant full control to the LocalSystem
                // account, (elevated) administrators, and the creator owner.
                // They also give only read access to members of the Everyone
                // group and the anonymous account. However, if you want to
                // customize the security permission of the pipe, (e.g. to allow
                // Authenticated Users to read from and write to the pipe), you
                // need to create a PipeSecurity object.
                PipeSecurity pipeSecurity = null;
                pipeSecurity = CreateSystemIOPipeSecurity();

                // Create the named pipe.
                pipeServer = new NamedPipeServerStream(
                    Program.PipeName,               // The unique pipe name.
                    PipeDirection.InOut,            // The pipe is duplex
                    NamedPipeServerStream.MaxAllowedServerInstances,
                    PipeTransmissionMode.Message,   // Message-based communication
                    PipeOptions.None,               // No additional parameters
                    Program.BufferSize,             // Input buffer size
                    Program.BufferSize,             // Output buffer size
                    pipeSecurity,                   // Pipe security attributes
                    HandleInheritability.None       // Not inheritable
                    );
                  Console.WriteLine("The named pipe ({0}) is created.",
                    Program.FullPipeName);

                // Wait for the client to connect.
                Console.WriteLine("Waiting for the client's connection...");
                pipeServer.WaitForConnection();
                Console.WriteLine("Client is connected.");

                //
                // Receive a request from client.
                //
                // Note: The named pipe was created to support message-based
                // communication. 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 the article:
                // http://go.microsoft.com/?linkid=9721786.
                //

                string message;

                do
                {
                    byte[] bRequest = new byte[Program.BufferSize];
                    int cbRequest = bRequest.Length, cbRead;

                    cbRead = pipeServer.Read(bRequest, 0, cbRequest);

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

                //
                // Send a response from server to client.
                //
                var proc = new System.Diagnostics.Process
                {
                    StartInfo = new System.Diagnostics.ProcessStartInfo
                    {
                        FileName = message,
                        Arguments = "",
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        CreateNoWindow = true
                    }
                };

                proc.Start();
                StringBuilder sb = new StringBuilder();
                while (!proc.StandardOutput.EndOfStream)
                {
                    string line = proc.StandardOutput.ReadLine();
                    // do something with line
                    sb.Append("\n" + line );
                }

                //System.Diagnostics.Process.Start(message);

                sb.Append("###AAA###" + proc.ExitCode + "###BBB###");
                message = sb.ToString();

                //System.Diagnostics.Process.Start("notepad");

                byte[] bResponse = Encoding.Unicode.GetBytes(message);
                int cbResponse = bResponse.Length;

                pipeServer.Write(bResponse, 0, cbResponse);

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

                // Flush the pipe to allow the client to read the pipe's contents
                // before disconnecting. Then disconnect the client's connection.
                pipeServer.WaitForPipeDrain();
                pipeServer.Disconnect();
            }
            catch (Exception ex)
            {
                Console.WriteLine("The server throws the error: {0}", ex.Message);
            }
            finally
            {
                if (pipeServer != null)
                {
                    pipeServer.Close();
                    pipeServer = null;
                }
            }
        }
Exemple #25
0
        private static void startServer(string pn, frm_main f)
        {
            Decoder decoder = Encoding.Default.GetDecoder();
            Byte[] bytes = new Byte[BufferSize];
            char[] chars = new char[BufferSize];
            int numBytes = 0;
            StringBuilder msg = new StringBuilder();
             NamedPipeServerStream pipeServer;
            try
            {
                pipeServer = new NamedPipeServerStream(pn, PipeDirection.In, 1,
                                                       PipeTransmissionMode.Message,
                                                       PipeOptions.Asynchronous);
                while (true)
                {
                    pipeServer.WaitForConnection();

                    do
                    {
                        msg.Length = 0;
                        do
                        {
                            numBytes = pipeServer.Read(bytes, 0, BufferSize);
                            if (numBytes > 0)
                            {
                                int numChars = decoder.GetCharCount(bytes, 0, numBytes);
                                decoder.GetChars(bytes, 0, numBytes, chars, 0, false);
                                msg.Append(chars, 0, numChars);
                            }
                        } while (numBytes > 0 && !pipeServer.IsMessageComplete);
                        decoder.Reset();
                        if (numBytes > 0)
                        {
                            //MESSAGE O
                            string json = msg.ToString();
                            JSONobject a = JsonConvert.DeserializeObject<JSONobject>(json);
                            switch (a.action)
                            {
                                case "dial":
                                    Debug.WriteLine("Call command from namedPipe...");
                                    f.changeState("dialing");
                                    f.setFocus();
                                    f.setNumber(a.data.telnr);
                                    break;
                            }

                            //ownerInvoker.Invoke(msg.ToString());
                        }
                    } while (numBytes != 0);
                    pipeServer.Disconnect();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// Send request with image and parametars.
        /// And recive processed image
        /// </summary>
        /// <param name="request"><see cref="https://github.com/Nedja995/npcv2/docs/named-pipe.md"/></param>
        /// <returns></returns>
        public byte[] Process(byte[] request)
        {
            IList<byte[]> image = new List<byte[]>();

            _pipeServer = null;
            try
            {
                // Prepare the security attributes (the pipeSecurity parameter in
                // the constructor of NamedPipeServerStream) for the pipe. This
                // is optional. If pipeSecurity of NamedPipeServerStream is null,
                // the named pipe gets a default security descriptor.and the
                // handle cannot be inherited. The ACLs in the default security
                // descriptor of a pipe grant full control to the LocalSystem
                // account, (elevated) administrators, and the creator owner.
                // They also give only read access to members of the Everyone
                // group and the anonymous account. However, if you want to
                // customize the security permission of the pipe, (e.g. to allow
                // Authenticated Users to read from and write to the pipe), you
                // need to create a PipeSecurity object.
                PipeSecurity pipeSecurity = null;
                pipeSecurity = CreateSystemIOPipeSecurity();

                // Create the named pipe.
                _pipeServer = new NamedPipeServerStream(
                    PipeName,               // The unique pipe name.
                    PipeDirection.InOut,            // The pipe is duplex
                    NamedPipeServerStream.MaxAllowedServerInstances,
                    PipeTransmissionMode.Message,   // Message-based communication
                    PipeOptions.None,               // No additional parameters
                    _bufferSize,             // Input buffer size
                    _bufferSize,             // Output buffer size
                    pipeSecurity,                   // Pipe security attributes
                    HandleInheritability.None       // Not inheritable
                    );

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

                // Wait for the client to connect.
                Console.WriteLine("Waiting for the client's connection...");
                _pipeServer.WaitForConnection();
                Console.WriteLine("Client is connected.");

                //
                string message;

                //
                // Send a response from server to client.
                //
                message = "Matrix4x4";//ResponseMessage;
                byte[] bResponse = Encoding.Unicode.GetBytes(message);
                int cbResponse = bResponse.Length;

                _pipeServer.Write(request, 0, request.Length);

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

                //
                // Receive a request from client.
                //
                // Note: The named pipe was created to support message-based
                // communication. 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 the article:
                // http://go.microsoft.com/?linkid=9721786.
                //
                do
                {
                    byte[] bRequest = new byte[_bufferSize];
                    int cbRequest = bRequest.Length, cbRead;

                    cbRead = _pipeServer.Read(bRequest, 0, cbRequest);

                    // SAVE TO ARRAY
                    image.Add(bRequest);

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

                // Flush the pipe to allow the client to read the pipe's contents
                // before disconnecting. Then disconnect the client's connection.
                _pipeServer.WaitForPipeDrain();
                _pipeServer.Disconnect();
            }
            catch (Exception ex)
            {
                Console.WriteLine("The server throws the error: {0}", ex.Message);
            }
            finally
            {
                if (_pipeServer != null)
                {
                    _pipeServer.Close();
                    _pipeServer = null;
                }
            }

            byte[] ret = new byte[image.Count * 1024];
            for (int i = 0; i < image.Count; i++)
            {
                for (int j = 0; j < 1024; j++)
                {
                    ret[i * 1024 + j] = image[i][j];
                }
            }

            return ret;
        }
    public static async Task ClientCloneTests()
    {
        const string pipeName = "fooClientclone";

        byte[] msg1 = new byte[] { 5, 7, 9, 10 };
        byte[] received0 = new byte[] { };
        byte[] received1 = new byte[] { 0, 0, 0, 0 };

        using (NamedPipeServerStream server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte))
        using (NamedPipeClientStream clientBase = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, PipeOptions.None))
        {
            await Task.WhenAll(server.WaitForConnectionAsync(), clientBase.ConnectAsync());

            using (NamedPipeClientStream client = new NamedPipeClientStream(PipeDirection.Out, false, true, clientBase.SafePipeHandle))
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    Assert.Equal(1, client.NumberOfServerInstances);
                }
                Assert.Equal(PipeTransmissionMode.Byte, client.TransmissionMode);

                Task clientTask = Task.Run(() => client.Write(msg1, 0, msg1.Length));
                int len1 = server.Read(received1, 0, msg1.Length);
                await clientTask;
                Assert.Equal(msg1.Length, len1);
                Assert.Equal(msg1, received1);

                // test special cases of buffer lengths = 0
                int len0 = server.Read(received0, 0, 0);
                Assert.Equal(0, len0);
                Assert.Equal(0, await server.ReadAsync(received0, 0, 0));
            }
        }
    }
Exemple #28
0
 private uint ReadNumberFromPipe(NamedPipeServerStream pipe)
 {
     byte[] buffer = new byte[4];
     pipe.Read(buffer, 0, buffer.Length);
     return BitConverter.ToUInt32(buffer, 0);
 }
    public static async Task ServerPInvokeChecks()
    {
        // calling every API related to server and client to detect any bad PInvokes
        using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.Out))
        {
            Task clientTask = Task.Run(() => StartClient(PipeDirection.In));
            server.WaitForConnection();

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

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

            await clientTask;
        }

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

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                Assert.Equal(0, server.InBufferSize);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                Assert.True(server.InBufferSize > 0);
            }
            else
            {
                Assert.Throws<PlatformNotSupportedException>(() => server.InBufferSize);
            }
            byte[] readData = new byte[] { 0, 1 };
            Assert.Equal(1, server.Read(readData, 0, 1));
            Assert.Equal(1, server.ReadAsync(readData, 1, 1).Result);
            Assert.Equal(123, readData[0]);
            Assert.Equal(124, readData[1]);
        }
    }
    public static void ClientCloneTests()
    {
        const string pipeName = "fooClientclone";
        
        byte[] msg1 = new byte[] { 5, 7, 9, 10 };
        byte[] received0 = new byte[] { };
        byte[] received1 = new byte[] { 0, 0, 0, 0 };

        using (NamedPipeServerStream server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte))
        {
            using (NamedPipeClientStream clientBase = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None))
            {
                Task clientTask = Task.Run(() =>
                {
                    clientBase.Connect();

                    using (NamedPipeClientStream client = new NamedPipeClientStream(PipeDirection.InOut, false, true, clientBase.SafePipeHandle))
                    {
                        client.Write(msg1, 0, msg1.Length);

                        int serverCount = client.NumberOfServerInstances;
                        Assert.Equal(1, serverCount);
                        Assert.Equal(PipeTransmissionMode.Byte, client.TransmissionMode);
                    }
                });

                server.WaitForConnection();
                int len1 = server.Read(received1, 0, msg1.Length);
                Assert.Equal(msg1.Length, len1);
                Assert.Equal(msg1, received1);

                // test special cases of buffer lengths = 0
                int len0 = server.Read(received0, 0, 0);
                Assert.Equal(0, len0);

                server.Write(received0, 0, 0);

                Task<int> serverTaskRead = server.ReadAsync(received0, 0, 0);
                serverTaskRead.Wait();
                Assert.Equal(0, serverTaskRead.Result);

                server.WriteAsync(received0, 0, 0).Wait();
            }
        }
    }